[英]python threading with lock gives identical values
這是一個有趣的代碼,盡管不是很實用,因為使用本地線程更好,但是我使用它來學習鎖。
import threading
import thread
import time
import random
count = 0
lock = threading.Lock()
def increment(num):
global count
with lock:
count += num
time.sleep(random.uniform(0.2, 1.5))
with lock:
print "t1: %f" % count
def decrement(num):
global count
with lock:
count -= num
time.sleep(random.uniform(0.2, 2.5))
with lock:
print "t2: %f" % count
if __name__ == "__main__":
threads = []
for i in range(5):
t1 = threading.Thread(target=increment, args=(random.random(),))
t2 = threading.Thread(target=decrement, args=(random.random(),))
t1.start(); t2.start()
threads.append(t1);threads.append(t2);
# Wait for all threads to complete
for t in threads:
t.join()
print "Done"
問題是為什么它打印相同的數字? 如果我在類似的方法中使用單個鎖:
def increment(num):
global count
with lock:
count += num
time.sleep(random.uniform(0.2, 1.5))
print "t1: %f" % count
然后按預期方式打印隨機數。
大多數情況下,當線程進入sleep
,CPU會將上下文切換到其他線程。
因此,在您的代碼中,兩個線程都已經完成了第一個with lock
塊的線程之后(即在兩個線程都更改了count
數值之后),它們都到達了with lock
塊的第二個線程。
因此,當count
到達第二個鎖定塊並打印count
數值時, count
不再更改並包含一個特定值。 (在increment
和decrement
之后,都with lock
塊完成第一個)。
如果要查看差異,請將其更改為此:
def increment(num):
global count
with lock:
count += num
time.sleep(random.uniform(0.2, 1.5))
print "t1: %f" % count
def decrement(num):
global count
with lock:
count -= num
time.sleep(random.uniform(0.2, 2.5))
print "t2: %f" % count
(您也可以刪除sleep
命令)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.