Python Multiple Threads with a shared variable

157 Views Asked by At

I think this question is trivial but I'm having difficulty interpreting similar questions on here. I have multiple threads processing my data sequentially using queuing. That works fine, but I also would like to have a global configuration variable that is currently passed to each thread that I can update when necessary.

for example, in my Main.py, I have a configuration initialized as follows:

import Application1 as app1
import Application2 as app2
#App3, App4 also exist the same as App2.

config = {'parameter_1': 'value1', 'parameter_2': [1,2,3,4]}

Application1 = app1.Application1(config, other_stuff, etc)
Application2 = app2.Application2(config, other_stuff_2, etc_2)

MainWindow.start()
processing.start()

In my next file, "Application1.py", i have the following:

class Application1(Thread):
    def __init__(self, config): #I am currently passing my global config settings as an arg
        Thread.__init__(self)
        self._stopevent = threading.Event()
        self.config = config 

    def run(self):
        do_stuff()

    def join(self, timeout=None):
        """ Stop the thread. """
        self._stopevent.set()
        Thread.join(self, timeout)

The same thing happens in my file "Application2.py. In "Application2", I would like to update the "config" variable so that it changes the next time "Application1" reads from it, whenever that may be (order is not important). I thought using global variables can fix this, but I read that using them is generally frowned upon. I am wondering what the most efficient way to do this would be. It isn't important to me what the order of threads read and write to this variable, I am looking for just the plain quickest method.

Please let me know if I should add any information to this question, Thanks!

0

There are 0 best solutions below