日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python 线程死锁_python线程死锁与递归锁

發布時間:2025/4/16 python 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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线程死锁与递归锁的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。