0

我认为这个问题是微不足道的,但我很难在这里解释类似的问题。我有多个线程使用排队顺序处理我的数据。这很好用,但我也希望有一个当前传递给每个线程的全局配置变量,我可以在必要时对其进行更新。

例如,在我的 Main.py 中,我的配置初始化如下:

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()

在我的下一个文件“Application1.py”中,我有以下内容:

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)

同样的事情发生在我的文件“Application2.py”中。在“Application2”中,我想更新“config”变量,以便它在下次“Application1”读取它时更改,无论何时(顺序并不重要)。我认为使用全局变量可以解决这个问题,但我读到使用它们通常是不受欢迎的。我想知道最有效的方法是什么。对我来说,线程读取的顺序和写入这个变量,我正在寻找最简单的方法。

如果我应该在这个问题中添加任何信息,请告诉我,谢谢!

4

0 回答 0