哲学家问题 |
转自http://www.eygle.com/unix/OS.Process.Lock.Latch.Semaphores.htm#1-1
一个房间内有5个哲学家,他们的生活就是思考和进食。房间里有一张圆桌,中间放着一盘通心粉(假定通心粉无限多)。桌子周围放有五把椅子,分别属于五位哲学家每两位哲学家之间有一把叉子,哲学家进食时必须同时使用左右两把叉子。 解答: 进程:philosopher - 哲学家 共有的数据结构&过程: state: array [0..4] of (think,hungry,eat); ph: array [0..4] of semaphore; — 每个哲学家有一个信号量,初值为0 mutex: semaphore; — mutex保护临界区,初值=1 procedure test(i:0..4); { if ((state[i]=hungry) and (state[(i+1)mod 5]<>eating) and (state[(i-1)mod 5]<>eating)) { state[i]=eating; V(ph[i]); } } philosopher(i:0..4): { while (true) { think(); p(mutex); state[i]=hungry; test(i); v(mutex); p(ph[i]); eat(); p(mutex); state[i]=think; test((i-1) mod 5); test((i+1) mod 5); v(mutex); } } |
进程的同步与互斥-哲学家问题
最新推荐文章于 2022-01-12 12:37:35 发布