首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >QThread中的std::condition_variable使用::run()

QThread中的std::condition_variable使用::run()
EN

Stack Overflow用户
提问于 2017-08-11 19:01:05
回答 1查看 315关注 0票数 0

我目前在QThread内部使用QThread时遇到了一个问题。当我在nofity_one方法中调用QThread::run()notify_all时,线程会崩溃("QThread:在线程仍在运行时销毁“)。

代码语言:javascript
复制
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应该是线程安全的。

你知道我的代码有什么问题吗?

提前感谢您的帮助!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-08-11 19:27:56

“IgorTandetnik”的评论帮助了我。我只是忘了在我的主要功能结束时调用QCoreApplication::exec()

这导致了我的线程被杀死的行为,因为我的主函数在它能够完成它的工作之前就超出了它的范围,这就导致了已经被删除的Qt事件循环访问对象。

代码语言:javascript
复制
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();
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45642158

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档