1. 程式人生 > >線程鎖(互斥鎖)

線程鎖(互斥鎖)

-s 等於 time reading 實的 部分 守護 lock 操作

1、線程鎖

  當我們執行多線程計算時,某些情況,會導致計算的結果,並不是我們想要的真實的結果。

  例如下面的例子,預計結果sum=50,實際中多次運算的結果中,某些情況,不等於50;

  

import threading
import time

def worker(n):
print ("threading [%s] is begin!" % n)
global sum
sum+=1
time.sleep(2)
print ("threading [%s] is end!" % n)
start_time = time.time()
sum = 0
for i in range(50):

t = threading.Thread(target=worker,args = ("Thread-[%s]" % i,))
#t.setDaemon(True)#將子線程設置為守護線程
t.start()
print ("all is done !")
cost_time = time.time() - start_time
print (sum)
print (cost_time)

針對上面的例子,我們需要在計算的時候,添加線程鎖,當填加了線程鎖後,各線程在執行計算操作時,實際上變為串行
import threading
import time

def worker(n):
print ("threading [%s] is begin!" % n)

lock.acquire()
global sum
sum+=1
lock.release()
print ("threading [%s] is end!" % n)
start_time = time.time()
sum = 0
lock = threading.Lock()
#res_list = []
for i in range(50):
t = threading.Thread(target=worker,args = ("Thread-[%s]" % i,))
t.start()
#res_list.append(t)
# for t in res_list:

# t.join()
print ("all is done !")
cost_time = time.time() - start_time
print (sum)
print (cost_time)

多上述的例子來看,理論上加了鎖,運行的結果,應該為想要的50,但從實際結果看,某些時候,依然運行不正確。
從結果看,有些線程未運行完成,主線程即結束了。如果加上join方法(即註釋部分代碼)後,多次結果的結果均為正確。
 

線程鎖(互斥鎖)