如何从GUI应用程序正确终止QThread?

Bo *_*ich 3 python qt multithreading pyqt

我尝试self.terminate()在QThread类中使用,也在self.thread.terminate()GUI类中使用.我也尝试self.wait()过两种情况.但是,有两种情况发生:

1)线程根本不终止,GUI冻结等待线程完成.线程完成后,GUI解冻,一切恢复正常.

2)线程确实终止,但同时冻结整个应用程序.

我也试过用self.thread.exit().没有快乐.

为了进一步说明,我试图在GUI中实现一个用户中止按钮,它将在任何时间点终止线程的执行.

提前致谢.

编辑:

这是run()方法:

def run(self):
    if self.create:
        print "calling create f"
        self.emit(SIGNAL("disableCreate(bool)"))
        self.create(self.password, self.email)
        self.stop()            
        self.emit(SIGNAL("finished(bool)"), self.completed)

def stop(self):
     #Tried the following, one by one (and all together too, I was desperate):
     self.terminate()
     self.quit()
     self.exit()
     self.stopped = True
     self.terminated = True
     #Neither works
Run Code Online (Sandbox Code Playgroud)

这是用于中止线程的GUI类的方法:

def on_abort_clicked(self):
     self.thread = threadmodule.Thread()
     #Tried the following, also one by one and altogether:
     self.thread.exit()
     self.thread.wait()
     self.thread.quit()
     self.thread.terminate()
     #Again, none work
Run Code Online (Sandbox Code Playgroud)

doc*_*eer 5

从QThread :: terminate的Qt文档:

警告:此功能很危险,不鼓励使用.线程可以在其代码路径中的任何位置终止.修改数据时可以终止线程.线程无法自行清理,解锁任何保持的互斥锁等.简而言之,只有在绝对必要时才使用此功能.

重新考虑你的线程策略可能是一个更好的想法,你可以使用QThread :: quit()来指示线程干净地退出,而不是试图让线程以这种方式终止.实际上从线程内调用thread.exit()应该这样做,具体取决于你如何实现run().如果您想共享线程运行方法的代码,可能会暗示它为什么不起作用.

  • 我也试过了。它碰巧有点工作(GUI 不会冻结,但线程也不会终止)。然而,最奇怪的事情刚刚发生。我删除了线程中的所有`def stop(self)`代码和GUI中的`def on_abort_clicked(self)`代码,并重新编写了它。我只是将 `self.terminate()` 放在线程的 `stop()` 函数中,并在 GUI 类中执行 `self.thread.stop()`。它就像一个魅力。AFAIK,这是我尝试的第一件事,之前没有奏效。我可能错过了一些东西。 (2认同)