簡體   English   中英

Python如何同步線程?

[英]Python how to synchronize threads?

我正在學習使用Python進行並發編程。

在以下代碼中,我似乎遇到了同步問題。 我該如何解決?

import threading
N = 1000000
counter = 0

def increment():
    global counter
    for i in range(N):
        counter += 1

t1 = threading.Thread(target=increment)
t2 = threading.Thread(target=increment)

t1.start()
t2.start()
t1.join()
t2.join()

print(counter)

兩個線程都試圖同時修改counter ,有時它們確實這樣做。 這導致一些增量不出現。 這是一種使用threading.Lock解決該問題的簡單方法:

import threading

N = 1000000
counter = 0

def increment(theLock):
    global counter
    for i in range(N):
        theLock.acquire()
        counter += 1
        theLock.release()

lock = threading.Lock()
t1 = threading.Thread(target=increment, args=[lock,])
t2 = threading.Thread(target=increment, args=[lock,])

t1.start()
t2.start()
t1.join()
t2.join()

print(counter)

必須保護theLock.acquire()theLock.release()環繞代碼,使其一次只能在一個線程中運行。 在您的例子中,獲取和釋放也可以圍繞整個環,但是這將是一樣沒有使用多。 請參閱線程文檔 ,尤其是“ Lock Objects部分。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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