在将对象移动到另一个线程后,是否不能简单地删除它?

时间:2015-02-26 13:04:55

标签: c++ multithreading qt

我原来的问题在这里: Deconstruct object gives QCoreApplication::sendEvent: "Cannot send events to objects owned by a different thread

我看到很多人说你移动到worketraread后就无法从gui线程中删除一个QObject。

像这样:

//In the GUI thread
QThread* workerThread = new QThread(this);
worker->moveToThread(workerThread);
...
//Still in the Gui thread but somewhere else
delete worker;//Is this wrong?

在这种情况下,如果我想在销毁 worker 时停止 workerthread ,那么我唯一的选择就是做以下事情:

connect(worerThread,&finished,worker,&deleteLater)?
...
//when I no longer need the worker & the worker thread
workerThread->quit();
workerThread->wait();

1 个答案:

答案 0 :(得分:3)

您可以而且应该使用

//Still in the Gui thread but somewhere else
worker->deleteLater();

然后在worker中删除了workerThread。此外,不需要停止workerThread

有关QObject::deleteLater()的更多信息,请参阅Qt文档。