簡體   English   中英

帶鎖的python線程給出相同的值

[英]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不再更改並包含一個特定值。 (在incrementdecrement之后,都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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM