Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save TommyWu-fdgkhdkgh/d65a759e10047d6cce8a461d1eda5be8 to your computer and use it in GitHub Desktop.

Select an option

Save TommyWu-fdgkhdkgh/d65a759e10047d6cce8a461d1eda5be8 to your computer and use it in GitHub Desktop.
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