刘工的思路非常混乱, 看程序, 看什么程序, 贴几行毫无用处代码的片段只能说明你缺乏基本的逻辑思维能力。另外: Fork 是叉子, 不是筷子。
那一段代码源自于 Modern Operating Systems 一书:
#define N 5 /*number of philosophers*/
#define LEFT (i+N-1)%N /*i's left neighbour*/
#define RIGHT (i+1)%N /*i's right neighbour*/
#define THINKING 0 /*philosopher is thinking*/
#define HUNGRY 1 /*philosopher is trying to get the forks*/
#define EATING 2 /*philosopher is eating*/
typedef int semaphore; /*semaphores are special kind of integers*/
int state[N]; /*array to keep track of everyone's state*/
semaphore mutex; /*mutual exclusion for critical regions (init 1)*/
semaphore s[N] ; /*one semaphore per philosopher (init 0)*/
void philosopher(int i) { /*i:philosopher number, from 0 to N-1*/
while (TRUE) { /*repeat forever*/
think(); /*philosopher is thinking*/
take_forks(i); /*acquire two forks or block*/
eat(); /*yum-yum, spaghetti*/
put_forks(i); /*put both forks back on table*/
}
}
void take_forks(int i) { /*i:philosopher number, from 0 to N-1*/
down(&mutex); /*enter critical region*/
state[i] = HUNGRY; /*record fact that philosopher is hungry*/
test(i); /*try to acquire 2 forks*/
up(&mutex); /*exit critical region*/
down(&s[i]); /*block if forks were not acquired*/
}
void put_forks(int i) { /*i:philosopher number, from 0 to N-1*/
down(&mutex); /*enter critical region*/
state[i] = THINKING; /*philosopher has finished eating*/
test (LEFT)); /*see if left neighbour can now eat*/
test (RIGHT); /*see if right neighbour can now eat*/
up(&mutex); /*exit critical region*/
}
void test (int i) { /*i:philosopher number, from 0 to N-1*/
if (state[i]==HUNGRY && state[LEFT]!=EATING && state[RIGHT]!=EATING) {
state[i] = EATING;
up(&s[i]);
}
} |