您的位置:首页 > 其它

进程的同步与互斥-哲学家问题

2014-09-02 23:55 309 查看
哲学家问题
转自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); 



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: