Page 1 of 1

help with threading module and passing global variables

Posted: Thu Feb 21, 2019 12:17 pm
by ricardo.santos
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

Code: Select all

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

Code: Select all

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

Posted: Thu Feb 21, 2019 1:49 pm
by MrYsLab
Below is a simple example of using a class to manage 2 threads. All variables declared with a prefix of "self." in the __init__ method of the class can be used by all methods of the class. No messing with globals (they are truly evil ;) )

In the example, both threads are modifying the "g" variable so I have added a data lock so that both threads do not access the variables at the same time.

Hopefully,

Code: Select all

import threading
import time


class MyPlayer(threading.Thread):

    def __init__(self):

        # initialize the inherited Thread object
        threading.Thread.__init__(self)
        self.daemon = True

        # create a data lock
        self.my_lock = threading.Lock()

        # a variable exclusively used by thread1
        self.t1 = 0

        # a variable exclusively used by thread2
        self.t2 = 0

        # a variable shared by both threads
        self.g = 0

        # start thread 1
        self.thread1()

    def thread1(self):
        # start the 2nd thread
        # you must start the 2nd thread using the name "start"
        self.start()
        while True:
            with self.my_lock:
                self.t1 += 1
                self.g = self.t1 + self.t2
            print('thread 1  t1:{} t2:{} g1:{}'.format(self.t1, self.t2, self.g))
            time.sleep(1)

    def run(self):
        """
        This the second thread's executable code. It must be called run.
        """
        while True:
            with self.my_lock:
                self.t2 += 1
                self.g = self.t1 + self.t2

            print('thread 2  t1:{} t2:{} g:{}'.format(self.t1, self.t2, self.g))
            time.sleep(2)


MyPlayer()
this helps you solve your issue.

Re: help with threading module and passing global variables

Posted: Thu Feb 21, 2019 2:12 pm
by ricardo.santos
thanks i will try it

Re: help with threading module and passing global variables

Posted: Thu Feb 21, 2019 2:57 pm
by ricardo.santos
here you have two threads inside a class.... in that way you can use self

but if you have different threads that are not in the same class. For example between the main program and a separate thread?

Re: help with threading module and passing global variables

Posted: Thu Feb 21, 2019 3:07 pm
by MrYsLab
I don't fully understand your question. The class runs 2 separate threads. The first is the method called thread1. The second is the run method which is invoked by thread1 calling start(). This may seem to be weird (and it is), but that is standard thread coding.

A threaded program runs within a single process. Are you trying to run your code in multiple processes? If you just want to use separate functions then that is what my code does, just organized as methods within a class.

Here is a good article on concurrency (running multiple things at the same time) that may help clear things up for you: https://realpython.com/python-concurren ... ng-version

Re: help with threading module and passing global variables

Posted: Thu Feb 21, 2019 4:02 pm
by ricardo.santos
thanks for help

Re: help with threading module and passing global variables

Posted: Tue Sep 03, 2019 11:01 am
by galewinston
In general however, you should avoid using global variables which become extremely quickly out of hand. And this is especially true for multi threaded programs, where you don't have any synchronization mechanism for your thread to know when purticular variable has been modified. In short: threads are complicated, and you cannot expect to have an intuitive understanding of the order in which events are happening when two (or more) threads work on the same value. The language, compiler, OS, processor... can ALL play a role, and decide to modify the order of operations for speed, practicality or any other reason.