python 學習第二十四天(同步鎖和遞迴鎖)
阿新 • • 發佈:2018-11-01
- 同步鎖
給一段程式碼加了同步鎖之後,在這段程式碼執行時只能有一個執行緒執行。
import time
import threading
def addNum():
global num #在每個執行緒中都獲取這個全域性變數
#num-=1
temp=num
#print('--get num:',num )
time.sleep(0.1)#可以把時間調短一點,看看是什麼效果
num =temp-1 #對此公共變數進行-1操作
num = 100 #設定一個共享變數
thread_list = []
for i in range(100):
t = threading.Thread(target=addNum)
t.start()
thread_list.append(t)
for t in thread_list: #等待所有執行緒執行完畢
t.join()
print('final num:', num )#結果為99,多個執行緒都在同時操作同一個共享資源,所以造成了資源破壞
加鎖後
import time
import threading
R = threading.Lock()
####
def sub():
global num
R.acquire() #
temp = num - 1 #
time.sleep(0.1) #
num = temp #這五行相當於序列,但如果後面還有程式碼就會是併發的
R.release() #
num=100
thread_list = []
for i in range(100):
t = threading.Thread(target=sub)
t.start()
thread_list.append(t)
for t in thread_list: #等待所有執行緒執行完畢
t.join()
print('final num:' , num )#結果是0
- 死鎖
線上程間共享多個資源的時候,如果兩個執行緒分別佔有一部分資源並且同時等待對方的資源,就會造成死鎖,因為系統判斷這部分資源都正在使用,所有這兩個執行緒在無外力作用下將一直等待下去。例子:
import threading,time
class myThread(threading.Thread):
def doA(self):
lockA.acquire()
print(self.name,"gotlockA",time.ctime())
time.sleep(3)
lockB.acquire()
print(self.name,"gotlockB",time.ctime())
lockB.release()
lockA.release()
def doB(self):
lockB.acquire()
print(self.name,"gotlockB",time.ctime())
time.sleep(2)
lockA.acquire()
print(self.name,"gotlockA",time.ctime())
lockA.release()
lockB.release()
def run(self):
self.doA()
self.doB()
if __name__=="__main__":
lockA=threading.Lock()
lockB=threading.Lock()
threads=[]
for i in range(5):
threads.append(myThread())
for t in threads:
t.start()
for t in threads:
t.join()#等待執行緒結束。#程式會在中間鎖死
- 遞迴鎖
為了解決死鎖問題
import threading,time
class myThread(threading.Thread):
def doA(self):
RL.acquire()
print(self.name,"gotlockA",time.ctime())
time.sleep(3)
RL.acquire()
print(self.name,"gotlockB",time.ctime())
RL.release()
RL.release()
def doB(self):
RL.acquire()
print(self.name,"gotlockB",time.ctime())
time.sleep(2)
RL.acquire()
print(self.name,"gotlockA",time.ctime())
RL.release()
RL.release()
def run(self):
self.doA()
self.doB()
if __name__=="__main__":
RL=threading.RLock()
threads=[]
for i in range(5):
threads.append(myThread())
for t in threads:
t.start()
for t in threads:
t.join()