简体   繁体   English

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

[英]Using global variables across files and threads in python

I have 2 files, first is file1.py我有 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()

And second is file2.py:第二个是file2.py:

import threading

def main_task():
    from file1 import counter
    global counter  

    
    counter = counter + 10

    print(counter)

I am trying to make it so that each thread adds 10 to the variable "counter".我正在尝试使每个线程将 10 添加到变量“计数器”中。 This is first defined as 0, but then I run 10 threads to each add 10 to it.这首先定义为 0,但随后我运行 10 个线程,每个线程添加 10。 My thinking is that at the end of every thread running, counter should be equal to 100, as they added 10 to it 10 times.我的想法是,在每个线程运行结束时,计数器应该等于 100,因为他们将 10 加到了 10 次。 I do see why this is not happening, as Import counter from file1, which is set as 0, but how do I make it so every task references the same counter variable and can add to it?我确实明白为什么没有发生这种情况,因为从文件 1 导入计数器,它设置为 0,但是我如何使它使每个任务都引用相同的计数器变量并可以添加到它?

You need to structure your code differently and instead of using a global variable use a synchronization primitive.您需要以不同的方式构造代码,而不是使用global变量,而是使用同步原语。 Here is one way to structure your code.这是构建代码的一种方法。

# 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM