QThread :: run()

时间:2017-08-11 19:01:05

标签: c++ c++11 stl qthread

我目前在std::condition_variable内使用QThread时遇到问题。 当我在nofity_one方法中调用notify_allQThread::run()时,我的线程崩溃了(" 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应该是线程安全的。

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

提前感谢您的帮助!

0 个答案:

没有答案