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

code
import time
from threading import Thread,Lock
noodle_lock = Lock()
fork_lock = Lock()
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 抢到了面条
^CException ignored in: <module 'threading' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py'>
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 1308, in _shutdown
    lock.acquire()
KeyboardInterrupt
macname@MacdeMacBook-Pro py % 

 

 
 
 
 
 
 
 
 
 
 

posted @ 2020-12-26 12:49  anobscureretreat  阅读(212)  评论(0编辑  收藏  举报