在python中跨文件和线程使用全局变量

在python中跨文件和线程使用全局变量,python,python-3.x,python-multithreading,Python,Python 3.x,Python Multithreading,我有两个文件,第一个是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 fil

我有两个文件,第一个是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)

我试图使每个线程向变量“counter”添加10。首先将其定义为0,然后我运行10个线程,每个线程添加10个线程。我的想法是,在每个线程运行结束时,计数器应该等于100,因为他们将10添加到它10次。我确实明白为什么不会发生这种情况,因为file1中的导入计数器被设置为0,但我如何使其成为每个任务都引用相同的计数器变量并可以添加到其中?

您需要以不同的方式构造代码,而不是使用
全局
变量,而是使用同步原语。这里有一种构造代码的方法

# 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

您需要使用适当的同步原语,而不是全局变量我想说的是创建一个包含变量的引用对象,并在调用时将其传递给每个线程,但是@gold\u cy需要适当的同步机制可能是正确的。此外,您当前的代码有一些循环引用,因为每个文件都互相导入,这是不好的practice@gold_cy我尝试添加同步,但仍然存在问题。问题不是将10添加到0的任务,而是file2中的task函数将不接受全局变量。如果我将file2中的所有内容都放到file1中,那么它就工作得非常好。问题是它们跨越2个文件,所以我想知道如何解决这个问题。