递归锁 其实就是维护一个计数器 比如A 线程 获得了锁 那么计数器会+1 释放的时候 为0 如果这个计数器不为0 那么其他的线程无法获得锁 只能慢慢的等待
import threading
import time
class MyThread(threading.Thread):
def actionA(self):
r_lcok.acquire() #count=1
print(self.name,"gotA",time.ctime())
time.sleep(2)
r_lcok.acquire() #count=2
print(self.name, "gotB", time.ctime())
time.sleep(1)
r_lcok.release() #count=1
r_lcok.release() #count=0
def actionB(self):
r_lcok.acquire()
print(self.name, "gotB", time.ctime())
time.sleep(2)
r_lcok.acquire()
print(self.name, "gotA", time.ctime())
time.sleep(1)
r_lcok.release()
r_lcok.release()
def run(self):
self.actionA()
self.actionB()
if __name__ == '__main__':
# A=threading.Lock()
# B=threading.Lock()
r_lcok=threading.RLock()
L=[]
for i in range(5):
t=MyThread()
t.start()
L.append(t)
for i in L:
i.join()
print("ending....")
Thread-1 gotA Sat Jan 26 11:24:35 2019
Thread-1 gotB Sat Jan 26 11:24:37 2019
Thread-1 gotB Sat Jan 26 11:24:38 2019
Thread-1 gotA Sat Jan 26 11:24:40 2019
Thread-3 gotA Sat Jan 26 11:24:41 2019
Thread-3 gotB Sat Jan 26 11:24:43 2019
Thread-3 gotB Sat Jan 26 11:24:44 2019
Thread-3 gotA Sat Jan 26 11:24:46 2019
Thread-5 gotA Sat Jan 26 11:24:47 2019
Thread-5 gotB Sat Jan 26 11:24:49 2019
Thread-5 gotB Sat Jan 26 11:24:50 2019
Thread-5 gotA Sat Jan 26 11:24:52 2019
Thread-4 gotA Sat Jan 26 11:24:53 2019
Thread-4 gotB Sat Jan 26 11:24:55 2019
Thread-4 gotB Sat Jan 26 11:24:56 2019
Thread-4 gotA Sat Jan 26 11:24:58 2019
Thread-2 gotA Sat Jan 26 11:24:59 2019
Thread-2 gotB Sat Jan 26 11:25:01 2019
Thread-2 gotB Sat Jan 26 11:25:02 2019
Thread-2 gotA Sat Jan 26 11:25:04 2019
ending....