05:死锁问题 --- 协程
1 所谓死锁:是指两个或两个以上的进程或线程在执行过程中,因争夺资源而造成的一种互相等待的现象,若无外力作用,它们都将无法推进下去。此时称系统处于死锁状态或系统产生了死锁,这些永远在互相等待的进程称为死锁进程,如下就是死锁
2 可重入锁,递归锁
# from threading import Thread, Lock # import time # import random # # # def eat1(lock_1, lock_2, name): # lock_1.acquire() # print('%s:拿到了筷子' % name) # time.sleep(random.random()) # lock_2.acquire() # print('%s:拿到了面条' % name) # print('开始吃面') # time.sleep(random.random()) # lock_2.release() # print('%s放下了面条' % name) # lock_1.release() # print('%s放下了筷子' % name) # # # def eat2(lock_1, lock_2, name): # lock_2.acquire() # print('%s:拿到了面条' % name) # time.sleep(random.random()) # lock_1.acquire() # print('%s:拿到了筷子' % name) # print('开始吃面') # time.sleep(random.random()) # lock_1.release() # print('%s放下了筷子' % name) # lock_2.release() # print('%s放下了面条' % name) # # # if __name__ == '__main__': # lock_1 = Lock() # lock_2 = Lock() # for i in ['张三', '李四', '王五']: # t = Thread(target=eat1, args=[lock_1, lock_2, i]) # t.start() # for i in ['赵6', '往7', '傻逼']: # t = Thread(target=eat2, args=[lock_1, lock_2, i]) # t.start() ### 解决死锁问题 RLock:可重入,可以重复acquire,获得几次,就要释放几次 from threading import Thread, Lock,RLock import time import random def eat1(lock_1, lock_2, name): lock_1.acquire() print('%s:拿到了筷子' % name) time.sleep(random.random()) lock_2.acquire() print('%s:拿到了面条' % name) print('开始吃面') time.sleep(random.random()) lock_2.release() print('%s放下了面条' % name) lock_1.release() print('%s放下了筷子' % name) def eat2(lock_1, lock_2, name): lock_2.acquire() print('%s:拿到了面条' % name) time.sleep(random.random()) lock_1.acquire() print('%s:拿到了筷子' % name) print('开始吃面') time.sleep(random.random()) lock_1.release() print('%s放下了筷子' % name) lock_2.release() print('%s放下了面条' % name) if __name__ == '__main__': lock_1 = RLock() lock_2 = lock_1 # lock_1 = Lock() # lock_2 = lock_1 for i in ['张三', '李四', '王五']: t = Thread(target=eat1, args=[lock_1, lock_2, i]) t.start() for i in ['赵6', '往7', '傻逼']: t = Thread(target=eat2, args=[lock_1, lock_2, i]) t.start()