同時提供可能會帶來死鎖的解法和不可能死鎖的解法
可能帶來死鎖
import threading
import time
import random
chopstick=
for i in
range(5
):1)
)class
philosopher
(threading.thread)
:def
__init__
(self,id)
: self.id=
id threading.thread.__init__(self)
defrun
(self)
:while1:
#思考print
('{}號哲學家開始思考'
.format
(self.id)
) time.sleep(random.uniform(
0.1,
0.5)
)#休息
print
('{}號哲學家開始休息'
.format
(self.id)
) time.sleep(random.uniform(
0.1,
0.5)
)#吃飯 i號(0到4)哲學家取i(0到4)號和i-1號筷子
chopstick[self.id]
.acquire(
) time.sleep(
0.3)
#增加死鎖的概率
chopstick[
(self.id-
1)%5
].acquire(
)print
('{}號哲學家開始吃飯'
.format
(self.id)
) time.sleep(random.uniform(
0.1,
0.5)
) chopstick[
(self.id-
1)%5
].release(
) chopstick[self.id]
.release(
)if __name__ ==
"__main__"
:for i in
range(5
):phi=philosopher(i)
phi.start(
)
執行結果如下,進入死鎖狀態
絕對不可能產生死鎖的解法
限制最多只有4個哲學家拿筷子,則不會產生死鎖
import threading
import time
import random
chopstick=
count=
0#統計拿著筷子的人數,最多只能有4個哲學家拿筷子
for i in
range(5
):1)
)class
philosopher
(threading.thread)
:def
__init__
(self,id)
: self.id=
id threading.thread.__init__(self)
defrun
(self)
:global chopstick,count
while1:
#思考print
('{}號哲學家開始思考'
.format
(self.id)
) time.sleep(random.uniform(
0.1,
0.5)
)#休息
print
('{}號哲學家開始休息'
.format
(self.id)
) time.sleep(random.uniform(
0.1,
0.5)
)if count<4:
#吃飯 i號(0到4)哲學家取i(0到4)號和i-1號筷子
count+=
1 chopstick[self.id]
.acquire(
) time.sleep(
0.5)
chopstick[
(self.id-
1)%5
].acquire(
)print
('{}號哲學家開始吃飯'
.format
(self.id)
) time.sleep(random.uniform(
0.1,
0.5)
) chopstick[
(self.id-
1)%5
].release(
) chopstick[self.id]
.release(
)if __name__ ==
"__main__"
:for i in
range(5
):phi=philosopher(i)
phi.start(
)
執行結果如下,哲學家們可以持續吃飯,沒有產生死鎖。
哲學家就餐
include include include include include include 筷子作為mutex pthread mutex t chopstick 6 void eat think void arg int i for pthread mutex lock chopstick r...
哲學家就餐問題
本文是哲學家就餐問題在 linux 上的程式實現,與windows 平台的實現類似,程式上稍有不同。philosopherdining.cpp include include include include include include rasutil.h using namespace std ...
哲學家就餐問題
pragma once include include include include include include include include include include include include include stdafx.h handle chopstick 5 room l...