死锁与递归锁
死锁导致程序卡死,
互斥锁只能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()