移动到其他线程后不能简单地删除对象?

3

我的原始问题在这里:解构对象会出现QCoreApplication::sendEvent: "不能向由不同线程拥有的对象发送事件

我看到很多人说,将QObject移动到工作线程后,就不能从GUI线程中删除它。

就像这样:

//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个回答

3

你可以而且应该使用

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

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

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


那么,从GUI线程中删除{worker}是不可以的吗?我提到的方法呢,也是安全的吗? - Nyaruko
使用delete删除对象是很危险的。在那个特定的时刻,该对象可能会被另一个线程使用(例如workerThread的事件循环)。 - Christian
дҪ зҡ„workerThreadеҸӘжү§иЎҢиҝҷдёҖдёӘд»»еҠЎеҗ—пјҹеҰӮжһңжҳҜиҝҷж ·пјҢиҜ·жҹҘзңӢQt ConcurrentгҖӮйӮЈд№ҲдҪ е°ұдёҚйңҖиҰҒеҲ йҷӨд»»дҪ•дёңиҘҝдәҶгҖӮ - Christian

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接