Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/155.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ std::condition_QThread::run()内的变量用法_C++_C++11_Stl_Qthread - Fatal编程技术网

C++ std::condition_QThread::run()内的变量用法

C++ std::condition_QThread::run()内的变量用法,c++,c++11,stl,qthread,C++,C++11,Stl,Qthread,在QThread内部使用std::condition\u变量时,我当前面临一个问题。 在QThread::run()方法中调用nofity\u one或notify\u all时,我的线程崩溃(“QThread:在线程仍在运行时销毁”) class-ThreadImpl:public-QThread { Q_对象 公众: ThreadImpl(QObject*parent=0); std::shared_ptr getmutexventisinit(); std::条件变量m_isInit; 受

QThread
内部使用
std::condition\u变量时,我当前面临一个问题。
在
QThread::run()
方法中调用
nofity\u one
notify\u all
时,我的线程崩溃(“QThread:在线程仍在运行时销毁”)

class-ThreadImpl:public-QThread
{
Q_对象
公众:
ThreadImpl(QObject*parent=0);
std::shared_ptr getmutexventisinit();
std::条件变量m_isInit;
受保护的:
无效运行();
私人:
可变std::共享的ptr m_pmutexeventinit;
可变QMutex m_mutexPtrConnection;
};
void AWSIoTConnectionUserRunner::run()
{

@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();
}
intmain(intargc,char*argv[])
{
qcorea应用程序(argc、argv);
ThreadImpl1impl;
impl.start();
//等待与init的连接
shared_ptr pMutexUserConnectionInit=impl.getmutexventisinit();
{
唯一的锁(*pMutexUserConnectionInit);
runnerUserConnection.m_isInit.wait(锁);
}

我不能确定,但也许Qt中线程的管理方式与std线程无关。这就是为什么条件变量不起作用。顺便说一句,你的线程管理是错误的。QThread并不意味着要继承,我怀疑你的程序确实达到了
cout@IgorTandetnik,谢谢你的回答。我刚刚意识到我犯了一个错误巨大的错误。我注释掉了“main”函数末尾的“QCoreApplication::exec()”调用。因此您的答案是正确的。
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();
}