死鎖與遞歸鎖
阿新 • • 發佈:2018-05-16
for lose -a int time chang 連續 bsp tar 死鎖導致程序卡死,
死鎖導致程序卡死,
互斥鎖只能acquire一次,想acquire必須先release。
from threading import Thread,Lock import time mutexA=Lock() mutexB=Lock() class MyThread(Thread): def __init__(self): super().__init__() def run(self): self.f1() self.f2() def f1(self): mutexA.acquire()print("%s mutex A" % self.name) time.sleep(1) mutexB.acquire() print("%s mutex B" % self.name) mutexA.release() mutexB.release() def f2(self): mutexB.acquire() print("%s mutex B" % self.name) time.sleep(1) mutexA.acquire()print("%s mutex A" % self.name) mutexA.release() mutexB.release() if __name__ == "__main__": for i in range(10): t=MyThread() t.start()奧
遞歸鎖,RLock,可以連續acquire()多次。RLock內部有一個計數器,每acquire()一次計數器加1,只要計數不為0就不能被其他線程搶到。
from threading import Thread,RLock import time mutexB=mutexA=RLock()
class MyThread(Thread): def __init__(self): super().__init__() def run(self): self.f1() self.f2() def f1(self): mutexA.acquire() print("%s mutex A" % self.name) time.sleep(1) mutexB.acquire() print("%s mutex B" % self.name) mutexA.release() mutexB.release() def f2(self): mutexB.acquire() print("%s mutex B" % self.name) time.sleep(1) mutexA.acquire() print("%s mutex A" % self.name) mutexA.release() mutexB.release() if __name__ == "__main__": for i in range(10): t=MyThread() t.start()View Code
死鎖與遞歸鎖