Question
How do I cause a deadlock in the following program: #include #include #include #include #include #include #include #include using namespace std; void *philosopher(void *param); const
How do I cause a deadlock in the following program:
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
void *philosopher(void *param);
const int NUM = 5;
std::mutex chopstick[NUM];
int main(){ pthread_t tid[NUM]; pthread_attr_t attr; pthread_attr_init(&attr); for(int i=0; i < NUM; i++){ int *num = new int; *num = i; pthread_create(&tid[i], &attr, philosopher, (void *)num); } while(1); //pthread_join(tid1, NULL); return 0; }
void *philosopher(void *param){ int i = *((int *)param); cout << "Registred philosopher: " << i << endl; while(1){ cout << "Philosopher " << i << " is thinking "; sleep(rand()%3); cout << "Philosopher " << i << " is hungry "; cout << "Philosopher " << i << " is waiting on another chopstick "; sleep(rand()%7); chopstick[i].unlock(); chopstick[(i+1)%NUM].unlock(); } }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started