[英]Using global variables across files and threads in python
我有 2 個文件,第一個是 file1.py
import threading
from file2 import main_task
global counter
counter = 0
for i in range(0,10):
thread1 = threading.Thread(target=main_task, )
thread1.start()
第二個是file2.py:
import threading
def main_task():
from file1 import counter
global counter
counter = counter + 10
print(counter)
我正在嘗試使每個線程將 10 添加到變量“計數器”中。 這首先定義為 0,但隨后我運行 10 個線程,每個線程添加 10。 我的想法是,在每個線程運行結束時,計數器應該等於 100,因為他們將 10 加到了 10 次。 我確實明白為什么沒有發生這種情況,因為從文件 1 導入計數器,它設置為 0,但是我如何使它使每個任務都引用相同的計數器變量並可以添加到它?
您需要以不同的方式構造代碼,而不是使用global
變量,而是使用同步原語。 這是構建代碼的一種方法。
# file1.py
from threading import Thread
def worker(counter):
counter.value += 10
def runner(counter):
for i in range(0, 10):
thread1 = Thread(target=worker, args=(counter,))
thread1.start()
# file2.py
from ctypes import c_int
from multiprocessing import Value
from file1 import runner
val = Value(c_int, 0)
runner(val)
print(val.value)
>> 100
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.