Philosopher's question

Source: Internet
Author: User
Tags usleep

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.