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

Python - Cannot join thread - No multiprocessing

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

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

join() raises a RuntimeError if an attempt is made to join the current thread as that would cause a deadlock. It is also an error to join() a thread before it has been started and attempts to do so raises the same exception.

我有一些坏消息。 Python 中的线程毫无意义,您最好只考虑使用 1 个线程或使用多进程。如果您需要查看线程,那么您将需要查看其他语言,如 C# 或 C。查看 https://docs.python.org/2/library/multiprocessing.html

线程在 python 中毫无意义的原因是全局解释器锁 (GIL)。这使您一次只能使用一个线程,因此 python 中没有多线程,但有人在处理它。 http://pypy.org/

正在等待加入

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

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

thread2.join()

"stop here and do not execute the next line of code until thread2 is finished".

如果您(在 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