从派生自 QThread 的 class 的析构函数手动调用 terminate() 和 quit() 是否安全?
Is it safe to call terminate() and quit() manually from a destructor of a class that was derived from QThread?
我想在我的应用程序被销毁时终止(完成)QThread。
因此,我在从`QThread 派生的 class 的 destructor
中调用 terminate()
和 quit()
。
安全吗?
class Session : public QThread
{
Q_OBJECT
private:
CheckerAdapter *inst;
public:
explicit Session(CheckerAdapter *inst, QObject *parent = 0);
void run();
~Session(){
terminate();
quit();
}
};
使用 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
,你需要有一种方法来告诉线程它必须终止,当线程得到它时,它应该 return 从它的 run()
尽快实施。 Qt 提供了两种方法来做到这一点:
- 如果你的线程运行是一个事件循环(即你不覆盖
run()
,或者如果你调用exec()
您的自定义 run()
实现),您可以从任何线程 调用 QThread::quit()
/QThread::exit()
。这将导致线程事件在处理完当前事件后立即循环到 return。没有数据损坏,因为当前处理没有终止。
- 如果你的线程没有运行事件循环,你可以使用
QThread::requestInterruption()
from any other thread to tell the thread that it should stop. But you have to handle that in your implementation of run()
using isInterruptionRequested()
(否则,调用 requestInterruption()
什么都不做)。
注:
如果您使用上述任何方法在其析构函数中停止 QThread
,您必须确保线程不再 运行ning QThread
对象被销毁,您可以通过在使用 quit()
/requestInterruption()
后 调用 QThread::wait()
来做到这一点。 =34=]
查看 this answer 以了解 QThread
子类的类似实现。
我想在我的应用程序被销毁时终止(完成)QThread。
因此,我在从`QThread 派生的 class 的 destructor
中调用 terminate()
和 quit()
。
安全吗?
class Session : public QThread
{
Q_OBJECT
private:
CheckerAdapter *inst;
public:
explicit Session(CheckerAdapter *inst, QObject *parent = 0);
void run();
~Session(){
terminate();
quit();
}
};
使用 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
,你需要有一种方法来告诉线程它必须终止,当线程得到它时,它应该 return 从它的 run()
尽快实施。 Qt 提供了两种方法来做到这一点:
- 如果你的线程运行是一个事件循环(即你不覆盖
run()
,或者如果你调用exec()
您的自定义run()
实现),您可以从任何线程 调用QThread::quit()
/QThread::exit()
。这将导致线程事件在处理完当前事件后立即循环到 return。没有数据损坏,因为当前处理没有终止。 - 如果你的线程没有运行事件循环,你可以使用
QThread::requestInterruption()
from any other thread to tell the thread that it should stop. But you have to handle that in your implementation ofrun()
usingisInterruptionRequested()
(否则,调用requestInterruption()
什么都不做)。
注:
如果您使用上述任何方法在其析构函数中停止 QThread
,您必须确保线程不再 运行ning QThread
对象被销毁,您可以通过在使用 quit()
/requestInterruption()
后 调用 QThread::wait()
来做到这一点。 =34=]
查看 this answer 以了解 QThread
子类的类似实现。