Search code examples
c++11condition-variable

why the condition_variable waits indefinitely


Consider the following code snippet

#include <future>

std::mutex asyncMut_;
std::atomic<bool> isAsyncOperAllowed = false;
std::condition_variable cv;

void asyncFunc()
{
    while (isAsyncOperAllowed)
    {
        std::unique_lock<std::mutex> ul(asyncMut_);
        cv.wait(ul, []()
        {
            return isAsyncOperAllowed == false;
        });
    }
}

int main()
{
    isAsyncOperAllowed = true;
    auto fut = std::async(std::launch::async, asyncFunc);

    std::this_thread::sleep_for(std::chrono::seconds(3));

    std::lock_guard<std::mutex> lg(asyncMut_);
    isAsyncOperAllowed = false;
    cv.notify_one();

    fut.get();
}

I am expecting that once I change the status of the isAsyncOperAllowed variable and notify the condition variable, the condition variable inside the asyncFunc should exit the wait and asyncFync should return and the main should end.

I am observing that the condition variable keeps waiting indefinitely. What am I doing wrong?

P.S. I am on Win10 - VS2015


Solution

  • Deadlock: main() never unlocks lg so even though the cv in asyncFunc() gets notified it never gets an opportunity to run since it can't claim the lock.

    Try:

    int main()
    {
        isAsyncOperAllowed = true;
        auto fut = std::async(std::launch::async, asyncFunc);
    
        std::this_thread::sleep_for(std::chrono::seconds(3));
    
        {
            std::lock_guard<std::mutex> lg(asyncMut_);
            isAsyncOperAllowed = false;
        }
        cv.notify_one();
    
        fut.get();
    }