![](/img/trans.png)
[英]Python parallel execution - threading.Lock not working as intentioned
[英]python threading.lock() not working
我創建了一個函數來修改一個全局變量,每次加 1。 然后我創建了 10 個線程來調用這個函數; 每個線程將調用該函數 10 次。 但是,變量的最終值與我在一個線程中調用函數 100 次不同。 我如何使用threading.lock
有什么問題嗎? 下面是我的代碼:
num=0
lockOne=threading.Lock()
def subPro():
global num
lockOne.acquire()
num+=1
lockOne.release()
您可能沒有等待線程完成。 你必須使用Thread.join :
import threading
num=0
lockOne=threading.Lock()
def subPro():
global num
lockOne.acquire()
num+=1
lockOne.release()
def run():
for i in range(10):
subPro()
# Start all threads
threads = [threading.Thread(target=run) for x in range(10)]
for thread in threads:
thread.start()
# Wait for completion
for thread in threads:
thread.join()
print(num)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.