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

标签 python multithreading wxpython

我的程序中有这段代码。其中 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”条件执行后加入线程。直到他们我希望线程运行。

最佳答案

正在等待加入

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

所以,在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

关于Python - 无法加入线程 - 没有多处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39903009/

相关文章:

python - 中止列表理解

python - 限制 Django Tastypie 中嵌套资源的数量?

java - 从使用线程的另一个类检索 String 时出现问题

c# - 在WPF UI线程中等待Dispatcher.Invoke

python - wxpython shell 启用向上箭头来检索命令

python - 使用 Celery 和 Python 将输入和图像处理作业发送到多台机器

android - Python 系统调用找不到文件,在 Apache 服务器上运行出错

multithreading - Java 线程中断对我不起作用(在 groovy 中)

python - 从其 wxPython 父级中删除一个小部件

java - 桌面 UI 设计工具,最好是 Java 或 Java 包装器