简体   繁体   中英

Using global variables across files and threads in python

I have 2 files, first is 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:

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". This is first defined as 0, but then I run 10 threads to each add 10 to it. 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. 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?

You need to structure your code differently and instead of using a global variable use a synchronization primitive. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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