python3 递归锁解决死锁问题

python

解决:典型死锁问题科学家吃面

code

import time

from threading import Thread, RLock

fork_lock = noodle_lock = RLock()

def eat1(name):

noodle_lock.acquire()

print('%s 抢到了面条' % name)

fork_lock.acquire()

print('%s 抢到了叉子' % name)

print('%s 吃面' % name)

fork_lock.release()

noodle_lock.release()

def eat2(name):

fork_lock.acquire()

print('%s 抢到了叉子' % name)

time.sleep(1)

noodle_lock.acquire()

print('%s 抢到了面条' % name)

print('%s 吃面' % name)

noodle_lock.release()

fork_lock.release()

for name in ['哪吒', 'nick', 'tank']:

t1 = Thread(target=eat1, args=(name,))

t2 = Thread(target=eat2, args=(name,))

t1.start()

t2.start()

outputs 

macname@MacdeMacBook-Pro py % python3 cccccc.py

哪吒 抢到了面条

哪吒 抢到了叉子

哪吒 吃面

哪吒 抢到了叉子

哪吒 抢到了面条

哪吒 吃面

nick 抢到了面条

nick 抢到了叉子

nick 吃面

nick 抢到了叉子

nick 抢到了面条

nick 吃面

tank 抢到了面条

tank 抢到了叉子

tank 吃面

tank 抢到了叉子

tank 抢到了面条

tank 吃面

macname@MacdeMacBook-Pro py %

 

 

 

 

 

 

 

 

 

 

 

以上是 python3 递归锁解决死锁问题 的全部内容, 来源链接: utcz.com/z/388986.html

回到顶部