1 ‘‘‘ 2 程序流程: 3 1、线程1先获得RLock 打印 Thread -1 拿到递归锁,RLock中的count+1 4 2、先成1 继续执行又一次拿到RLock 打印Thread -1 拿到递归锁,此时的count变为2 5 3、释放一次递归锁count变为1 6 4、再释放一次递归锁count 变为0 7 5、此时其他的线程有可能进来或者线程1继续执行func2 ,如果线程1抢到递归锁,那么其他线程继续等待,如果其他的线程拿到,那么线程1等待直到拿到递归锁 8 9 10 ‘‘‘ 11 12 13 14 from threading import Thread,Lock 15 import threading 16 import time 17 # mutexA=Thread.RLock() 18 # mutexB=Lock() 19 r_lock= threading.RLock() 20 class MyThread(Thread): 21 def run(self): 22 self.func1() 23 self.func2() 24 def func1(self): 25 r_lock.acquire() 26 print(‘\033[41m%s 拿到A锁\033[0m‘ %self.name) 27 28 r_lock.acquire() 29 print(‘\033[42m%s 拿到B锁\033[0m‘ %self.name) 30 r_lock.release() 31 32 r_lock.release() 33 34 def func2(self): 35 r_lock.acquire() 36 print(‘\033[43m%s 拿到B锁\033[0m‘ %self.name) 37 time.sleep(2) 38 39 r_lock.acquire() 40 print(‘\033[44m%s 拿到A锁\033[0m‘ %self.name) 41 r_lock.release() 42 43 r_lock.release() 44 45 if __name__ == ‘__main__‘: 46 for i in range(10): 47 t=MyThread() 48 t.start()
#其结果会出现如下图:所有的线程都会执行
原文:https://www.cnblogs.com/luncky/p/11800040.html