python锁有哪几种_python 可重入锁有什么用?
可重入鎖:支持在同一線程中多次請求同一資源
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()
還是我學藝不精,說可重入鎖是用來防止死鎖的,那么可重入鎖應該用在什么情況下?
總結
以上是生活随笔為你收集整理的python锁有哪几种_python 可重入锁有什么用?的全部內容,希望文章能夠幫你解決所遇到的問題。
                            
                        - 上一篇: esp32原理图设计_第十一章 ESP3
 - 下一篇: linux mint 无法联网_Linu