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

问题描述:

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

I tried using self.terminate() in the QThread class, and also self.thread.terminate() in the GUI class. I also tried putting self.wait() in both cases. However, there are two scenarios that happen:

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

1) The thread does not terminate at all, and the GUI freezes waiting for the thread to finish. Once the thread finished, the GUI unfreezes and everything is back to normal.

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

2) The thread indeed does terminate, but at the same time it freezes the entire application.

我也尝试使用self.thread.exit().没事.

为进一步澄清,我正在尝试在GUI中实现一个用户中止按钮,该按钮将在任何时间点终止线程的执行.

To further clarify, I am trying to implement a user-abort button in GUI which would terminate the executing of the thread at any point in time.

谢谢.

这是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类的方法:

And here is the GUI class' method for aborting the thread:

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

来自Qt的QThread文档:: terminate:

From the Qt documentation for QThread::terminate:

警告:此功能很危险,不建议使用.这 线程可以在其代码路径中的任何位置终止.线程可以是 在修改数据时终止.线程没有机会 自行清理后,解锁所有保持的互斥锁等.简而言之,请使用 仅在绝对必要时使用此功能.

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()的方式执行此操作.如果您想共享线程运行方法的代码,这可能会提示为什么它不起作用.

It's probably a much better idea to re-think your threading strategy such that you can e.g. use QThread::quit() to signal the thread to quit cleanly, rather than trying to get the thread to terminate this way. Actually calling thread.exit() from within the thread should do that depending on how you have implemented run(). If you'd like to share the code for your thread run method that might hint as to why it doesn't work.