Python--day41--递归锁Rlock
1,递归锁Rlock:递归锁是为了解决死锁问题,且递归锁的特点是在同一个线程中可以被acquire()多次
多个acquire()在递归锁中不会阻塞,而互斥锁Lock就会阻塞
代码示例:
1 from threading import RLock 2 3 rlock = RLock() 4 #多个acquire()在递归锁中不会阻塞,而线程锁Lock就会阻塞 5 rlock.acquire() 6 rlock.acquire() 7 rlock.acquire() 8 rlock.acquire() 9 print(123)
运行结果:
2,递归锁图示:(本质上为一串钥匙)
3,递归锁解决科学家吃面问题:
1 import time 2 from threading import RLock, Thread 3 4 noodle_lock = fork_lock = RLock() #一个钥匙串上的两把钥匙 5 6 def eat1(name): 7 noodle_lock.acquire() #一把钥匙,说明一串钥匙都在我手上了 8 print('%s拿到面了'%name) 9 fork_lock.acquire() 10 print('%s拿到叉子了'%name) 11 print('%s吃面'%name) 12 fork_lock.release() 13 noodle_lock.release() 14 15 def eat2(name): 16 fork_lock.acquire() 17 print('%s拿到叉子了' % name) 18 time.sleep(1) 19 noodle_lock.acquire() 20 print('%s拿到面了'%name) 21 print('%s吃面'%name) 22 noodle_lock.release() 23 fork_lock.release() 24 25 Thread(target=eat1,args=('alex',)).start() 26 Thread(target=eat2,args=('Egon',)).start() 27 Thread(target=eat1,args=('bossjin',)).start() 28 Thread(target=eat1,args=('nezha',)).start()
运行结果: