我目前在QThread内部使用QThread时遇到了一个问题。当我在nofity_one方法中调用QThread::run()或notify_all时,线程会崩溃("QThread:在线程仍在运行时销毁“)。
class ThreadImpl : public QThread
{
Q_OBJECT
public:
ThreadImpl(QObject* parent = 0);
std::shared_ptr<std::mutex> GetMutexEventIsInit();
std::condition_variable m_isInit;
protected:
void run();
private:
mutable std::shared_ptr<std::mutex> m_pMutexEventIsInit;
mutable QMutex m_mutexPtrConnection;
};
void AWSIoTConnectionUserRunner::run()
{
cout << DBGFUNC_CPP << endl;
{
// do init work here
// inform all 'waiters' that connection is initialized
m_isInit.notify_one();
}
exec(); // <-- crashes here inside event-loop
cout << DBGFUNC_CPP << "- quits." << endl;
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
ThreadImpl impl;
impl.start();
// wait for connection to init
shared_ptr<mutex> pMutexUserConnectionInit = impl.GetMutexEventIsInit();
{
unique_lock<mutex> lock(*pMutexUserConnectionInit);
runnerUserConnection.m_isInit.wait(lock);
}
cout << "This text never appears, because my program crashes before with:" << endl;
cout << "QThread: Destroyed while thread is still running"
}我知道在这个问题上存在QWaitCondition,但我只是不明白为什么它不能与STL中的一个一起工作。此外,我还假设造成崩溃的原因是访问了一个元素,该元素不是由线程创建的,但据我所知,std::condition_variable应该是线程安全的。
你知道我的代码有什么问题吗?
提前感谢您的帮助!
发布于 2017-08-11 19:27:56
“IgorTandetnik”的评论帮助了我。我只是忘了在我的主要功能结束时调用QCoreApplication::exec()。
这导致了我的线程被杀死的行为,因为我的主函数在它能够完成它的工作之前就超出了它的范围,这就导致了已经被删除的Qt事件循环访问对象。
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
ThreadImpl1impl;
impl.start();
// wait for connection to init
shared_ptr<mutex> pMutexUserConnectionInit = impl.GetMutexEventIsInit();
{
unique_lock<mutex> lock(*pMutexUserConnectionInit);
runnerUserConnection.m_isInit.wait(lock);
}
cout << "This text never appears, because my program crashes before with:" << endl;
cout << "QThread: Destroyed while thread is still running"
// This is what I forgot:
return a.exec();
}https://stackoverflow.com/questions/45642158
复制相似问题