std::condition_variable QThread::run() 中的用法

std::condition_variable usage inside QThread::run()

我目前在 QThread 中使用 std::condition_variable 时遇到问题。 当我在 QThread::run() 方法中调用 nofity_onenotify_all 时,我的线程崩溃了 ("QThread: Destroyed while thread is still running").

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应该是线程安全的。

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

在此先感谢您的帮助!

@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();
}