python多執行緒上鎖
阿新 • • 發佈:2019-02-15
一般談到多執行緒就會涉及到上鎖的問題, 為什麼要上鎖? 是為了執行緒安全. 比方說我有兩個執行緒, 都要拿到一個唯一的資料(只能被拿一次), 如果不上鎖, 那麼就很有可能兩個執行緒同時拿, 資料就被拿了兩次. 如果我們上鎖, 我們就限制了拿的操作在某個時間只能有一個執行緒做, 如果這個時候其他執行緒也想做就得等待. 這樣就保證了執行緒安全.
執行緒不安全的例子:
import threading, time
a = 1
def get():
global a
if(a):
time.sleep(1)
print(a)
a -= 1
threads = []
for i in range(0, 10):
t = threading.Thread(target = get)
threads.append(t)
for t in threads:
t.start()
for t in threads:
t.join()
本來輸出的結果應該只有一個 ’ 1 ’ , 但是實際的輸出卻有0甚至是負數, 這就是執行緒不安全造成的, 多個執行緒同時通過了if判斷, 然後輸出了異常的值, 所以這個時候我們就需要上鎖
import threading, time
a = 1
lock = threading.Lock()
def get():
global a
lock.acquire()
if(a):
time.sleep(1)
print(a)
a -= 1
lock.release()
threads = []
for i in range(0, 10):
t = threading.Thread(target = get)
threads.append(t)
for t in threads:
t.start()
for t in threads:
t.join()
這樣一來結果就對了