gpt4 book ai didi

c++ - 解构对象给出 QCoreApplication::sendEvent:“无法将事件发送到不同线程拥有的对象

转载 作者:行者123 更新时间:2023-11-28 02:32:02 27 4
gpt4 key购买 nike

我的代码太长了,这里是相关部分:

videoClass::videoClass()
{
...
QThread* workerThread = new QThread(this);
camwrk = new cameraWorker(workerThread);
camwrk->moveToThread(workerThread);
// There are many cross thread signal slot connections happening between this and the camwrk
}

videoClass::~videoClass()
{
...

delete camwrk;
...
}

cameraWorker::cameraWorker(QThread* workerThread)
{
_belongingThread = workerThread;
...
}

cameraWorker::cameraWorker(QThread* workerThread)
{
_belongingThread = workerThread;
...
}

cameraWorker::~cameraWorker()
{
_belongingThread->quit();
_belongingThread->wait();
}

每次当 _belongingThread->wait();完成后,我收到消息:

QCoreApplication::sendEvent: "Cannot send events to objects owned by a different thread

这里发生了什么?我认为这是使用 QThread 并完成它的正确方法吗?

最佳答案

QThread对象本身属于主线程:

It is important to remember that a QThread instance lives in the old thread that instantiated it, not in the new thread that calls run().

显然,QThread::wait() 是通过事件实现的。由于 cameraWorker 本身在 workerThread 上运行,而不是在 videoClass 的线程上运行,因此您不能使用它。

话虽如此,您当前的逻辑似乎有点太复杂了。你想在 cameraWorker 被销毁时停止线程,并且你想在它的父级也被销毁时销毁 camera worker:

QThread* workerThread = new QThread(this);

connect(camwrk, SIGNAL(destroyed()), workerThread, SLOT(quit()));
connect(this, SIGNAL(destroyed()), camwrk, SLOT(deleteLater()));

如果您想在 workerThread 完成执行后删除它,只需连接 finished()deleteLater():

connect(workerThread, SIGNAL(finished()),
workerThread, SLOT(deleteLater()));

但是,请记住 ~videoClass() 将调用 workerThread 的析构函数。确保线程在对象被销毁之前不再运行,或者简单地从 new QThread(this) 中删除 this 以防止所有权。

关于c++ - 解构对象给出 QCoreApplication::sendEvent:“无法将事件发送到不同线程拥有的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28741579/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com