Each time a chopstick is acquired, it causes a deadlock.
The solution is to try to get the two chopsticks you need each time. Get the left one for the first time and the second time to the right.
Only when two of them have been acquired, do they eat. Otherwise you will release all the chopsticks you have obtained.
This will prevent the deadlock.
#include <stdio.h>#include<unistd.h>#include<stdlib.h>#include<pthread.h>pthread_mutex_t chopsticks[5];voidFuninti) { intK =0; while(k< -){ if(Pthread_mutex_trylock (&chopsticks[i]) = =0){ if(Pthread_mutex_trylock (&chopsticks[(i+1)%5])==0) {printf ("Zhexuejia%d is eatinging\n", i); k++; Usleep (Ten); Pthread_mutex_unlock (&Chopsticks[i]); Pthread_mutex_unlock (&chopsticks[(i+1)%5]); }Else{printf ("Zhexuejia%d is thinking\n", i); k++; Pthread_mutex_unlock (&Chopsticks[i]); Usleep (Ten); } }Else{printf ("Zhexuejia%d is thinking\n", i); k++; Usleep (Ten); } }}intMain () {intt =0; while(t<5) {Pthread_mutex_init (&chopsticks[t],null); T++; } pthread_t TID1,TID2,TID3,TID4,TID5; Pthread_create (&tid1,null, (void*) Fun,0); Pthread_create (&tid2,null, (void*) Fun,1); Pthread_create (&tid3,null, (void*) Fun,2); Pthread_create (&tid4,null, (void*) Fun,3); Pthread_create (&tid5,null, (void*) Fun,4); Pthread_join (Tid1,null); Pthread_join (Tid2,null); Pthread_join (Tid3,null); Pthread_join (Tid4,null); Pthread_join (tid5,null);}
Philosopher's question