The question of the Philosopher's meal

Source: Internet
Author: User
Tags semaphore

Go directly to the code

1 #defineN 5/* Number of philosophers */2 #defineTheir neighbourhood number of left (i+n-1)%N/* I */3 #defineRight (i+ 1)%N/* I number */4 #defineThinking 0/* philosopher in thinking * *5 #defineHungry 1/* philosopher tries to pick up a fork */6 #defineEATING 2/* Philosopher's Dinner * *7typedefintSemaphore/*Signal Volume*/8 intState[n];/*record each philosopher's state*/ 9Semaphore Mutex =1;/*Mutual exclusion of critical sections*/TenSemaphore S[n];/*each philosopher a semaphore*/ One  A voidPhilosopher (intI/*I: Philosopher number, from 0 to N-1*/  - {  -      while(TRUE) {/*Infinite Loops*/ theThink ();/*Philosophers Thinking*/ -Take_ Forks (i);/*Test if the fork is available*/ -Eat ();/*Philosophers Dine*/ -Put_ Forks (i);/*put the fork back on the table*/  + } - } +  A voidTake_forks (intI at {   -Down (&mutex);/*Enter the critical section*/  -State[i] = hungry;/*record philosopher I in a state of starvation*/  -Test (i);/*try to get two forks*/  -Up (&mutex);/*Exit critical Section*/  -Down (&s[i]);/*If you don't get the fork you need, it's blocked.*/  in } -   to voidPut_forks (i) + {  -Down (&mutex);/*Enter the critical section*/  theState[i] =thinking;/*The philosopher is finished eating*/  *Test (left);/*test whether their neighbourhood can eat*/  $Test (right);/*test whether the right neighbor can eat*/ Panax NotoginsengUp (&mutex);/*leave the critical section*/  - }  the  + voidTest (i)
A { the if(State[i] ==hungry && state[left]! = EATING && state[right]! =EATING) { +State[i] =EATING; -Up (&S[i]); $ } $}

A philosopher is allowed to enter the dining state only when two neighbors are not eating!

The question of the Philosopher's meal

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.