可重入锁:支持在同一线程中多次请求同一资源
import threading
import time
class MyThread(threading.Thread):
def run(self):
global num
time.sleep(1)
if mutex.acquire(1):
num = num+1
msg = self.name+' set num to '+str(num)
print(msg)
mutex.acquire()
print('Do another thing.')
mutex.release()
mutex.release()
num = 0
mutex = threading.RLock()
def test():
for i in range(5):
t = MyThread()
t.start()
if __name__ == '__main__':
test()
那我既然一个线程要用两次共享变量,我直接acquire后我就不release,干嘛要acquire两次不是多此一举?
直接只有一次acquire和一次release:
import threading
import time
class MyThread(threading.Thread):
def run(self):
global num
time.sleep(1)
if mutex.acquire(1):
num = num+1
msg = self.name+' set num to '+str(num)
print(msg)
print('Do another thing.')
mutex.release()
num = 0
mutex = threading.RLock()
def test():
for i in range(5):
t = MyThread()
t.start()
if __name__ == '__main__':
test()
还是我学艺不精,说可重入锁是用来防止死锁的,那么可重入锁应该用在什么情况下?
可重入锁不是这么用的,一般是在面向对象中使用,比如
调用顺序不同,而且都需要同步的时候,如果不用递归锁,会死锁。如果f1或f2不加锁,数据不同步,报错