为什么condition_variable无限期等待

时间:2017-04-24 06:57:05

标签: c++11 condition-variable

请考虑以下代码段

#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();
}

我希望一旦我更改isAsyncOperAllowed变量的状态并通知条件变量,asyncFunc中的条件变量应该退出等待,asyncFync应该返回并且main应该结束。

我观察到条件变量一直无休止地等待。我做错了什么?

P.S。我在Win10 - VS2015

1 个答案:

答案 0 :(得分:2)

死锁:main()永远不会解锁lg所以即使cv中的asyncFunc()收到通知,它也永远不会有机会运行,因为它无法声明锁。

尝试:

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();
}