c++ - 了解使用 std::condition_variable 的示例

标签 c++ multithreading c++11

有一个使用 condition_variable 的例子来自 cppreference.com :

#include <condition_variable>
#include <mutex>
#include <thread>
#include <iostream>
#include <queue>
#include <chrono>

int main()
{
    std::queue<int> produced_nums;
    std::mutex m;
    std::condition_variable cond_var;
    bool done = false;
    bool notified = false;

    std::thread producer([&]() {
        for (int i = 0; i < 5; ++i) {
            std::this_thread::sleep_for(std::chrono::seconds(1));
            std::lock_guard<std::mutex> lock(m);
            std::cout << "producing " << i << '\n';
            produced_nums.push(i);
            notified = true;
            cond_var.notify_one();
        }   

        std::lock_guard<std::mutex> lock(m);  
        notified = true;
        done = true;
        cond_var.notify_one();
    }); 

    std::thread consumer([&]() {
        while (!done) {
            std::unique_lock<std::mutex> lock(m);
            while (!notified) {  // loop to avoid spurious wakeups
                cond_var.wait(lock);
            }   
            while (!produced_nums.empty()) {
                std::cout << "consuming " << produced_nums.front() << '\n';
                produced_nums.pop();
            }   
            notified = false;
        }   
    }); 

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

如果在消费者线程启动之前变量done变为true,消费者线程将不会收到任何消息。事实上,sleep_for(seconds(1)) 几乎可以避免这种情况,但是理论上是否可行(或者如果没有sleep在代码中)?

在我看来,正确的版本应该是这样的,以强制至少运行一次消费者循环:

std::thread consumer([&]() {
    std::unique_lock<std::mutex> lock(m);
    do {
        while (!notified || !done) {  // loop to avoid spurious wakeups
            cond_var.wait(lock);
        }   

        while (!produced_nums.empty()) {
            std::cout << "consuming " << produced_nums.front() << '\n';
            produced_nums.pop();
        }   

        notified = false;
    } while (!done);
}); 

最佳答案

是的,您完全正确:有一种(远程)可能性,消费者线程只有在 done 设置之后才会开始运行。此外,生产者线程中对done 的写入和消费者线程中的读取会产生竞争条件,并且行为未定义。你的版本也有同样的问题。在 each 函数中将互斥体包裹在整个循环中。抱歉,没有精力编写正确的代码。

关于c++ - 了解使用 std::condition_variable 的示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15733887/

相关文章:

c++ - 具有引用语义的 Const 对象

c++ - 线程池实现

c++ - 为什么连接多个字符串时性能会有所不同?

python - 在python中同步2个线程

c++ - 有没有办法在 Visual Studio 2012 中使用委托(delegate)构造函数?

c++ - C++11 线程是否为分离线程提供了一种在主线程退出后继续运行的方法?

c++ - 如何保存一个指针地址,以便另一个指针可以继续工作?

c++ - Qt - 非常简单的切换 Action 绘图

c++ - 对于重载的静态成员函数没有可行的重载 '='

multithreading - Erlang在运行并发任务时没有使用所有CPU核心,为什么?