[英]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.