为什么在我们已经有通知变量时使用condition_variable?

时间:2016-01-26 22:01:59

标签: c++ multithreading condition-variable

请考虑以下代码:

int main() { 
    bool done = false; 
    condition_variable con;
    mutex m;

    thread producer([&]() {
        this_thread::sleep_for(chrono::seconds(10)); 
        done = true;
        //con.notify_one();
    });

    thread consumer([&]() {
        /*unique_lock<mutex> lock(m);
        while (!done) {
            con.wait(lock);
        }*/
        while (!done);
        cout << "now my turn..."<<endl;
    });

    producer.join();
    consumer.join(); 
}

如果我取消注释2个线程中的代码,我将使用condition_variable。所以消费者线程看起来像这样:

thread consumer([&]() {
    unique_lock<mutex> lock(m);
    while (!done) {
        con.wait(lock);
    } 
    // while (!done); <-this is equivalent of the above
    cout << "now my turn..."<<endl;
});

似乎我可以使用/不使用condition_variable来实现相同的功能。 所以我的问题是:如果已经使用了通知变量(在这种情况下已完成&#39;变量),为什么我们需要condition_variable?使用它有什么好处?我可以做一些通知变量不能做的事情吗?

1 个答案:

答案 0 :(得分:5)

当等待条件变量时,线程被阻塞(即不执行)。当被通知时,线程处于就绪状态,因此操作系统可以安排它。

这比线程&#34;忙等待&#34;更有效,它不断地轮询变量以检查它是否可以继续。在这种情况下,线程正在耗尽可用于实际工作的CPU周期。

此外,您需要使用条件变量才能正确保护关键部分不被多个线程一次访问。您可能有3个消费者正在运行,但一次只允许一个消费者工作(其他人可能会在此之前做其他事情)。