Python - 无法加入线程 - 没有多处理

新手上路,请多包涵

我的程序中有这段代码。其中 OnDone 函数是 wxPython GUI 中的一个事件。当我单击“完成”按钮时,将触发 OnDone 事件,然后执行一些功能并启动线程 self.tstart - 目标函数为 StartEnable。我想使用 self.tStart.join() 加入这个线程。但是我收到如下错误:

 Exception in thread StartEnablingThread:
Traceback (most recent call last):
  File "C:\Python27\lib\threading.py", line 801, in __bootstrap_inner
    self.run()
  File "C:\Python27\lib\threading.py", line 754, in run
    self.__target(*self.__args, **self.__kwargs)
  File "//wagnernt.wagnerspraytech.com/users$/kundemj/windows/my documents/Production GUI/Trial python Codes/GUI_withClass.py", line 638, in StartEnable
    self.tStart.join()
  File "C:\Python27\lib\threading.py", line 931, in join
    raise RuntimeError("cannot join current thread")
RuntimeError: cannot join current thread

我以前没有遇到过这种类型的错误。你们中的任何一个人都可以告诉我我在这里缺少什么。

     def OnDone(self, event):
        self.WriteToController([0x04],'GuiMsgIn')
        self.status_text.SetLabel('PRESSURE CALIBRATION DONE \n DUMP PRESSURE')
        self.led1.SetBackgroundColour('GREY')
        self.add_pressure.Disable()
        self.tStart = threading.Thread(target=self.StartEnable, name = "StartEnablingThread", args=())
        self.tStart.start()

    def StartEnable(self):
        while True:
            time.sleep(0.5)
            if int(self.pressure_text_control.GetValue()) < 50:
                print "HELLO"
                self.start.Enable()
                self.tStart.join()
                print "hello2"
                break

我想在“if”条件执行后加入线程。直到他们我希望线程运行。

原文由 Jesh Kundem 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.5k
2 个回答

等待加入

加入 一个线程实际上意味着等待另一个线程完成。

所以,在 thread1 中,可以有这样的代码:

 thread2.join()

这意味着 “在 thread2 完成之前不要执行下一行代码”

如果您执行了(在 thread1 中)以下操作,则会因问题错误而失败:

 thread1.join()    # RuntimeError: cannot join current thread

加入不会停止

调用 thread2.join() 不会导致 thread2 停止,甚至不会以任何方式向它发出停止信号。

线程在其目标函数退出时停止。通常,一个线程被实现为一个循环,它检查一个告诉它停止的信号(一个变量),例如

def run():
    while whatever:
        # ...
        if self.should_abort_immediately:
            print 'aborting'
            return

然后,停止线程的方法是:

 thread2.should_abort_immediately = True  # tell the thread to stop
thread2.join()  # entirely optional: wait until it stops

问题代码

该代码已经使用 break 正确实现了停止。 join 应该被删除。

         if int(self.pressure_text_control.GetValue()) < 50:
            print "HELLO"
            self.start.Enable()
            print "hello2"
            break

原文由 zvone 发布,翻译遵循 CC BY-SA 3.0 许可协议

当执行 StartEnable 方法时,它运行在你在--- __init__ 方法中创建的StartEnablingThread上。您无法加入当前线程。这在 加入 调用的文档中有明确说明。

如果尝试加入当前线程,join() 会引发 RuntimeError,因为这会导致死锁。在线程启动之前加入()它也是一个错误,并且尝试这样做会引发相同的异常。

原文由 TWReever 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题