等待QMutex断言

时间:2015-06-22 17:58:29

标签: c++ multithreading qt

我发现即使是对QMutex的简单等待也会导致断言。我可能做错了什么?

QMutex mutex;

SyncMgr::SyncMgr(QObject *parent) : QObject(parent)
{
    moveToThread( &thread  );

    thread.start();

    process = new QProcess( this);

    connect( process, SIGNAL(readyReadStandardOutput()), this, SLOT(onReadyReadStandardOutput() ) );
    connect( process, SIGNAL(readyReadStandardError()), this, SLOT(onReadyReadStandardError() ) );
}

SyncMgr::~SyncMgr()
{
    delete process;
}

void SyncMgr::onConnected()
{
    cmdDispatcher.sendGetSerialNo();

    // this asserts
    waitForResponse.wait( &mutex ); // waitForResponse is CWaitCondition object

    // ...
}

我得到断言,错误信息是:

  

ASSERT:'copy'在线程\ qmutex.cpp,第525行

1 个答案:

答案 0 :(得分:1)

您需要在调用waitForResponse.wait()之前锁定互斥锁。 SyncMgr :: onConnected()方法应如下所示:

void SyncMgr::onConnected()
{
    cmdDispatcher.sendGetSerialNo();

    mutex.lock();
    waitForResponse.wait( &mutex );
    // do something
    mutex.unlock();

    ...
}

您可以在此处找到更多信息: http://doc.qt.io/qt-5/qwaitcondition.html#wait