我的代码太长,无法发布,下面是相关的部分:
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并完成它的正确方法吗?
发布于 2015-02-26 04:05:48
QThread
对象本身属于主线程:
重要的是要记住,
QThread
实例存在于实例化它的旧线程中,而不是在调用run()
的新线程中。
显然,QThread::wait()
是通过事件实现的。由于cameraWorker
本身运行在workerThread
上,而不是在videoClass
的线程上,所以不能使用它。
话虽如此,你目前的逻辑似乎有点复杂。当cameraWorker
被销毁时,您想要停止线程,当它的父程序也被销毁时,您想要销毁相机工作者:
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
的析构函数。确保在销毁对象之前线程不再运行,或者简单地从this
中删除new QThread(this)
以防止所有权。
https://stackoverflow.com/questions/28741579
复制相似问题