vendredi 11 août 2017

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

I'm currently facing a problem in using std::condition_variableinside QThread. When I call nofity_oneor notify_allinside the QThread::run() method my thread crashes ("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()
{
    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"
}

I know that there is QWaitConditionfor this matter but I just don't get why it does not work with the one of the STL. Additionally I also assume that the crash is caused because an element is accessed which was not created by the thread but as far as I know std::condition_variableshould be thread-safe.

Do you know what is wrong in my code?

Thanks in advance for your help!

Aucun commentaire:

Enregistrer un commentaire