Created
July 6, 2019 06:04
-
-
Save TommyWu-fdgkhdkgh/d65a759e10047d6cce8a461d1eda5be8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| monitor DiningPhilosophers | |
| { | |
| enum {THINKING, HUNGRY, EATING} state[5]; | |
| condition self[5]; | |
| void pickup(int i){ | |
| state[i] = HUNGRY; | |
| test(i); | |
| //假如沒辦法拿到筷子,進入condition variable self[i]的queue | |
| if(state[i] != EATING){ | |
| self[i].wait(); | |
| } | |
| } | |
| void putdown(int i){ | |
| state[i] = THINKING; | |
| //通知自己旁邊的哲學家,假如有人餓肚子(HUNGRY)的話,可以試著拿起筷子了。 | |
| test((i+4) % 5); | |
| test((i+1) % 5); | |
| } | |
| void test(int i){ | |
| //看自己的左邊與右邊的哲學家都沒在吃東西(沒拿起筷子),就可以開始吃了 | |
| if((state[(i+4) % 5] != EATING) && (state[i] == HUNGRY) && (state[(i+1) % 5] != EATING)){ | |
| state[i] = EATING; | |
| self[i].signal(); | |
| } | |
| } | |
| //對condition variable進行初始化 | |
| initialization_code(){ | |
| for(int i = 0; i < 5; i++){ | |
| state[i] = THINKING; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment