Search code examples
pythonmultithreadingglobal-variables

How to maintain Global variable across threads in python?


I have the following structure in my project.

file1.py

def run_tasks_threads():
    task1 = threading.Thread(target=do_task_1)
    task1.start()
    ...

from file2 import DO_OR_NOT

def do_task_1():
    while True:
        print DO_OR_NOT
        if DO_OR_NOT:
            # do something

file2.py

DO_OR_NOT = True

def function1:
    global DO_OR_NOT
    # modify DO_OR_NOT

run_tasks_threads is called from yet another file. And as in this code, it starts task1 as a new thread.

My problem is that modification of DO_OR_NOT from function1 is not getting reflected in task1()(new thread)!

Note: This is actually a part of my Django server.
function1 gets called multiple times.


Solution

  • The threading.Event() class provides you an interface for setting, clearing and getting boolean flags between threads.

    In the file1.py, an event variable has to be passed to the function that creates the thread, and then to the target function:

    def run_tasks_threads(my_event):
        task1 = threading.Thread(target=do_task_1, args=(my_event,)
        task1.start()
    
    def do_task_1(my_event):
        while True:
            print my_event.is_set()
            if my_event.is_set():
                # do something
    

    Finally, in the main script that calls the previous functions, the event has to be updated every time you call the function1:

    def main():
        #Create an instance of the event class
        my_event = threading.Event()
        file1.run_tasks_threads(my_event)
        while True
            global DO_OR_NOT
            #Get the bool value
            file2.function1()
            #Update the event flag depending on the boolean value
            if DO_OR_NOT:
                my_event.set()
            else:
                my_event.clear()