首页 > 解决方案 > Python无法从线程更新

问题描述

我正在为另一个应用程序编写第三方插件。我需要在单独的线程中运行一些代码,但似乎没有在单独的线程中运行任何代码。

这是一个基本示例

from threading import Thread
from time import sleep
from _Framework.ControlSurface import ControlSurface

class Collab(ControlSurface):
    def __init__(self, c_instance):
        ControlSurface.__init__(self, c_instance)

        # self.log_message is inherited from c_instance, logs
        # to the main app's log folder 
        self.log_message("COLLAB INIT")

        Thread(target=self.run_in_thread).start()
        self.log_message("Thread should run")
        sleep(5)
        self.log_message("Still waiting")
        sleep(5)

    def run_in_thread(self):
        sleep(1)
        self.log_message("Called from thread")

输出将是

COLLAB INIT
Thread should run
Still Waiting

Called From thread永远不会被记录。

我已经尝试了我能想到的所有变体,我已经尝试锁定线程。我尝试在线程中运行无限循环并验证线程是否仍在运行(它是),我尝试修改共享全局变量。线程中运行的任何内容似乎都无法输出任何内容,或影响任何其他变量。

标签: pythonmultithreading

解决方案


推荐阅读