死锁状态
from multiprocessing import Process from multiprocessing import Lock,RLock def func(lock): lock.acquire() # 持有锁 print('子进程成功拿锁') lock.acquire() # 持有锁 print('子进程再次成功拿锁') lock.release() # 使用release() 释放资源 lock.release() return def main(): l = RLock() # 使用Lock()会发生死锁,使用RLock()避免死锁 p = Process(target=func,args=(l,)) p.start() p.join() if __name__ == '__main__': main()
比较两个进程认识死锁
from multiprocessing import Process from multiprocessing import Lock,RLock import time def a(l1,l2): l1.acquire() # 持有l1锁 print('a进程拿到了l1锁') time.sleep(3) # 加时间体现死锁状态 l2.acquire() # 持有l2锁 print('a进程拿到了l2锁') print('a进程运行中') l1.release() l2.release() def b(l1,l2): l2.acquire() # 持有l2锁 print('b进程拿到了l2锁') l1.acquire() # 持有l1锁 print('b进程拿到了l1锁') print('b进程运行中') l2.release() l1.release() def main(): l1 = RLock() # 使用Lock()会发生死锁,使用RLock()避免死锁 l2 = RLock() # 使用Lock()会发生死锁,使用RLock()避免死锁 p1 = Process(target=a,args=(l1,l2)) p2 = Process(target=b,args=(l1,l2)) p1.start() p2.start() p1.join() p2.join() if __name__ == '__main__': main()
来源:https://www.cnblogs.com/xinzaiyuan/p/12452646.html