如何更新正在运行的线程中的变量,该线程是基于此类变量的无限循环?
我尝试过的简化版本如下所示,但毫无结果,而且我找不到任何指针。

import some_module as mod
import threading

class thr (threading.Thread):
    NUM = 5  # set a default value to start the script
    def run (self):
        mod.NUM = NUM
        mod.main_loop()

try:
    thr().start()
    time.sleep(1)
    thr().NUM = 2
    time.sleep(1)
    thr().NUM = 6
    time.sleep(1)
    thr().NUM = 8

最佳答案

问题是您每次“调用”(即实例化)thr时都在创建一个新线程。将您的代码更改为

t = thr()
t.start()
time.sleep(1)
t.NUM = 2
time.sleep(1)
t.NUM = 6
time.sleep(1)
t.NUM = 8
time.sleep(1)

关于python - python-更新线程变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37578254/

10-12 22:48