Python Forum
help with threading module and passing global variables - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: help with threading module and passing global variables (/thread-16285.html)



help with threading module and passing global variables - ricardons - Feb-21-2019

Hi

I'm having a big trouble to get this to work.

I have a function that I want to put in a thread (or multiprocess). This function requires 3 variables.
One of the variables (var_1) is static and no problem passing it through args in the thread module.
The second variable (var_2) changes during the main program

The last variable (flag) i want to use as a trigger when it gets True in the main program.


The "mental" structure of the program should be:

main.py

import threading
from test import function
import time

global flag, var_2

var_1 = "var_1"

t = threading.Thread(target=function, args=(var_1,))
t.start()

while True:
    var_2 = "var_2 (that changes in each while loop"
    flag = True
    time.sleep(1)
    flag = False
test.py

def function(var_1):
    global var_2, flag
    while True:

        if flag == True:
            print(var_1 + var_2)
But this does not work i think

Someone guru could help me?


RE: help with threading module and passing global variables - stullis - Feb-21-2019

First, as a maxim, don't use globals. They're more trouble than they're worth.

Second, you need a thread safe data structure to conduct this operation. "Thread safe" means that the variable can only be accessed by one thread at a time which ensures consistency when any thread uses it. Without thread safety, there may be the possibility of thread1 evaluating the variable, thread 2 changes it, and then thread 1 runs a calculation with the changed variable and gets a nonsensical result. Read up on multithreading locks. Once a lock is implemented, the function will need the variable as an argument.