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

标签 python multithreading qt pyqt

我尝试在 QThread 类中使用 self.terminate(),也在 GUI 类中使用 self.thread.terminate()。我还尝试在这两种情况下都放置 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

这是 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

最佳答案

来自 QThread::terminate 的 Qt 文档:

Warning: This function is dangerous and its use is discouraged. The thread can be terminated at any point in its code path. Threads can be terminated while modifying data. There is no chance for the thread to clean up after itself, unlock any held mutexes, etc. In short, use this function only if absolutely necessary.

重新考虑您的线程策略可能是一个更好的主意,例如,您可以使用 QThread::quit() 来指示线程干净地退出,而不是试图让线程以这种方式终止。实际上,从线程内调用 thread.exit() 应该根据您实现 run() 的方式来执行此操作。如果您想分享线程运行方法的代码,可能会提示它为什么不起作用。

关于python - 如何从 GUI 应用程序正确终止 QThread?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7928044/

相关文章:

像 C++ std::endl 这样的 Python 换行常量

Python重命名文件从csv文件中读取名称

c - 一个很好的应用程序,可以看到多线程的好处

java - 经典的读者-作者算法——使用单个锁有什么问题吗?

c++ - 将 vera++(或其他编码约定工具)与 Qt/QtCreator 集成

python - 没有名为 builtins 的模块

python - 处理从损坏的 GZ (TAR) 中提取单个文件

python - 如何检测Python线程是否被杀死?

c++ - 在 Qt 中,我怎么知道我在 foreach 中的最后一个对象

c++ - CodeBlocks Qt HelloWorld.exe 已停止工作 (C++)