python 线程死锁_python线程死锁与递归锁
死鎖現象
所謂死鎖: 是指兩個或兩個以上的進程或線程在執行過程中,因爭奪資源而造成的一種互相等待的現象,若無外力作用,它們都將無法推進下去。
此時稱系統處于死鎖狀態或系統產生了死鎖,這些永遠在互相等待的進程稱為死鎖進程,如下就是死鎖
from threading import Thread,Lock
import time
mutexA = Lock()
mutexB = Lock()
class MyThread(Thread):
def run(self):
self.task1()
self.task2()
def task1(self):
mutexA.acquire()
print('%s task1 get A' %self.name)
mutexB.acquire()
print('%s task1 get B' % self.name)
mutexB.release()
mutexA.release()
def task2(self):
mutexB.acquire()
print('%s task2 get B' % self.name)
time.sleep(1) # Thread-2 拿到執行權,執行get A出現死鎖,此時thread2需要B鎖,而thread1占用,與此同時,thread1需要A鎖,thread2占用
mutexA.acquire()
print('%s task2 get A' % self.name)
mutexA.release()
mutexB.release()
if __name__ == '__main__':
for i in range(10):
t = MyThread()
t.start()
-------------------輸出
Thread-1 task1 get A
Thread-1 task1 get B
Thread-1 task2 get B
Thread-2 task1 get A # 出現死鎖,整個程序被阻塞
遞歸鎖
解決方法,遞歸鎖,在Python中為了支持在同一線程中多次請求同一資源,python提供了可重入鎖RLock。
這個RLock內部維護著一個Lock和一個counter變量,counter記錄了acquire的次數,從而使得資源可以被多次require。
直到一個線程所有的acquire都被release,其他的線程才能獲得資源。上面的例子如果使用RLock代替Lock,則不會發生死鎖,二者的區別是:遞歸鎖可以連續acquire多次,而互斥鎖只能acquire一次
from threading import Thread,RLock
import time
mutexA = mutexB = RLock()
class MyThread(Thread):
def run(self):
self.task1()
self.task2()
def task1(self):
mutexA.acquire()
print('%s task1 get A' %self.name)
mutexB.acquire()
print('%s task1 get B' % self.name)
mutexB.release()
mutexA.release()
time.sleep(1) # Thread-2 拿到執行權,,此時counter=0,thread2執行task1
def task2(self):
mutexB.acquire()
print('%s task2 get B' % self.name)
mutexA.acquire()
print('%s task2 get A' % self.name)
mutexA.release()
mutexB.release()
if __name__ == '__main__':
for i in range(10):
t = MyThread()
t.start()
------------------------輸出
Thread-1 task1 get A
Thread-1 task1 get B
Thread-2 task1 get A
Thread-2 task1 get B
Thread-3 task1 get A
Thread-3 task1 get B
Thread-4 task1 get A
Thread-4 task1 get B
Thread-5 task1 get A
Thread-5 task1 get B
Thread-6 task1 get A
Thread-6 task1 get B
Thread-7 task1 get A
Thread-7 task1 get B
Thread-8 task1 get A
Thread-8 task1 get B
Thread-9 task1 get A
Thread-9 task1 get B
Thread-10 task1 get A
Thread-10 task1 get B
Thread-1 task2 get B
Thread-1 task2 get A
Thread-2 task2 get B
Thread-2 task2 get A
Thread-4 task2 get B
Thread-4 task2 get A
Thread-3 task2 get B
Thread-3 task2 get A
Thread-5 task2 get B
Thread-5 task2 get A
Thread-6 task2 get B
Thread-6 task2 get A
……
總結
以上是生活随笔為你收集整理的python 线程死锁_python线程死锁与递归锁的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql 平均日营业额_一条SQL语句
- 下一篇: java在哪个文件夹_JVM具体在哪个文