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

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!