1. 程式人生 > 其它 >執行緒死鎖和遞迴鎖

執行緒死鎖和遞迴鎖

'''


import threading
import time
class mythread(threading.Thread):
def A(self):
locka.acquire() #獲取鎖
print(self.name,"getlocka",time.ctime())
time.sleep(3)
lockb.acquire()
print(self.name,"getlockb",time.ctime())
lockb.release() #釋放鎖
locka.release()


def B(self):
lockb.acquire()
print(self.name,"getlockb",time.ctime())
time.sleep(2)
locka.acquire()
print(self.name,"getlocka",time.ctime())
locka.release()
lockb.release()
def run(self):
self.A()
self.B()

if __name__=="__main__":
locka=threading.Lock()
lockb=threading.Lock()
threads=[]

for i in range(5):
threads.append(mythread())#mythread()為例項化物件;將例項化5次並追加到列表中
print(threads)
for t in threads: #遍歷列表中的例項化物件,分分別進行啟動,並呼叫其中run方法
t.start()
for t in threads:
t.join()
'''
'''
#輸出結果:
Thread-1 getlocka Wed Jan 5 15:58:16 2022
Thread-1 getlockb Wed Jan 5 15:58:19 2022
Thread-1 getlockb Wed Jan 5 15:58:19 2022
Thread-2 getlocka Wed Jan 5 15:58:19 2022
當迴圈將執行緒追加到threads列表中以後,首先將執行緒1取出去呼叫run方法,當執行緒1獲取到鎖A,去執行列印,然後去獲取B鎖,執行列印
隨後釋放B鎖,A鎖;同時執行緒1去執行B函式獲取b鎖,並列印;再休息了2s後想要去獲取A鎖,而與此同時執行緒2已經執行了A函式獲取了A鎖將要獲取B鎖,
因為執行緒1沒有執行到釋放B鎖,執行緒2沒法拿到B鎖,執行緒2沒有釋放A鎖,執行緒1沒有辦法拿到B鎖;導致程式無法執行,死在當前程式中
'''
# 解決方法使用,遞迴鎖,其就是一把鎖,而此鎖可以被重複使用
# 如下:
import threading
import time
class mythread(threading.Thread):
def A(self):
lock.acquire()
print(self.name,"getlocka",time.ctime())
time.sleep(3)
lock.acquire()
print(self.name,"getlockb",time.ctime())
lock.release()
lock.release()


def B(self):
lock.acquire()
print(self.name,"getlockb",time.ctime())
time.sleep(2)
lock.acquire()
print(self.name,"getlocka",time.ctime())
lock.release()
lock.release()
def run(self):
self.A()
self.B()

if __name__=="__main__":
# locka=threading.Lock()
# lockb=threading.Lock()
lock=threading.RLock() #建立遞迴鎖
threads=[]

for i in range(5):
threads.append(mythread())#mythread()為例項化物件;將例項化5次並追加到列表中
print(threads)
for t in threads: #遍歷列表中的例項化物件,分分別進行啟動,並呼叫其中run方法
t.start()
for t in threads:
t.join()
#輸出結果:
"""
Thread-1 getlocka Wed Jan 5 17:18:39 2022
Thread-1 getlockb Wed Jan 5 17:18:42 2022
Thread-2 getlocka Wed Jan 5 17:18:42 2022
Thread-2 getlockb Wed Jan 5 17:18:45 2022
Thread-2 getlockb Wed Jan 5 17:18:45 2022
Thread-2 getlocka Wed Jan 5 17:18:47 2022
Thread-4 getlocka Wed Jan 5 17:18:47 2022
Thread-4 getlockb Wed Jan 5 17:18:50 2022
Thread-4 getlockb Wed Jan 5 17:18:50 2022
Thread-4 getlocka Wed Jan 5 17:18:52 2022
Thread-1 getlockb Wed Jan 5 17:18:52 2022
Thread-1 getlocka Wed Jan 5 17:18:54 2022
Thread-3 getlocka Wed Jan 5 17:18:54 2022
Thread-3 getlockb Wed Jan 5 17:18:57 2022
Thread-3 getlockb Wed Jan 5 17:18:57 2022
Thread-3 getlocka Wed Jan 5 17:18:59 2022
Thread-5 getlocka Wed Jan 5 17:18:59 2022
Thread-5 getlockb Wed Jan 5 17:19:02 2022
Thread-5 getlockb Wed Jan 5 17:19:02 2022
Thread-5 getlocka Wed Jan 5 17:19:04 2022

"""
對於A方法,當獲取到大鎖的時候,再去獲取小鎖,然後分別釋放小鎖和大鎖完畢以後,所有執行緒都會去搶獲取鎖的資源,誰先搶到,哪個執行緒則會進行執行