Search code examples
c++c++11mutexcondition-variable

If mutex is not locked before std::condition_variable::wait method, will mutex gets locked automatically?


In this snippet code below, if mutex is not locked before 'cv.wait' would it lock it automatically? I am getting some weird behaviour. These two parts are connected to each other.

#part1

{
    std::mutex& mtx = CoordPlaybackMediator::GetMutex();
    std::unique_lock<std::mutex> uniqueLock(mtx);
    CoordPlaybackMediator::SetPlayBackReadyFlag(true);
    uniqueLock.unlock(); 
    CoordPlaybackMediator::GetCV().notify_one();
    std::condition_variable& cv = CoordPlaybackMediator::GetCV();
    cv.wait(uniqueLock, []()->bool {return CoordPlaybackMediator::GetCoordReadyFlag(); }); 
    CoordPlaybackMediator::ResetCoorAndPlayBackFlags();
    uniqueLock.unlock();

    for (short int i = 0; i < WaveOutBufferThread::NUM_THREAD; ++i)
    {
        this->poWaveOutBufferThreadArray[i]->Play(i);
    }
}

#part 2

{
    std::mutex& mtx = CoordPlaybackMediator::GetMutex();
    std::unique_lock<std::mutex> uniqueLock(mtx);
    CoordPlaybackMediator::GetCV().wait(uniqueLock, []()->bool {return CoordPlaybackMediator::GetPlayBackReadyFlag(); });
    uniqueLock.unlock();

    for (size_t i = 0, counter = 0; i < this->pFileThreadInstance->GetCurrentWaveFileSize(); i += StepSize, counter += 1)
    {
        Debug::out("chunk%d : %2d \n", counter, i);     
    }
    
    this->status = STATUS::EMPTY; 
    std::unique_lock<std::mutex> uniqueLock2(CoordPlaybackMediator::GetMutex());
    CoordPlaybackMediator::SetCoordReadyFlag(true);
    uniqueLock2.unlock();
    CoordPlaybackMediator::GetCV().notify_one();
}

Solution

  • No, the mutex will not be locked.

    std::condition_variable's various wait() methods require the specified mutex to be locked by the execution thread that calls them. It's undefined behavior, otherwise, and you cannot expect any specific results, by definition.