Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/126.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 理解使用std::condition_变量的示例_C++_Multithreading_C++11 - Fatal编程技术网

C++ 理解使用std::condition_变量的示例

C++ 理解使用std::condition_变量的示例,c++,multithreading,c++11,C++,Multithreading,C++11,有一个使用条件变量的示例取自: 是的,您完全正确:在设置done之前,使用者线程可能(远程)不会开始运行。此外,生产者线程中的写入done和消费者线程中的读取产生竞争条件,并且行为未定义。你的版本也有同样的问题。在每个函数中围绕整个循环包装互斥锁。很抱歉,我没有精力编写正确的代码。无论如何,这是可怕的代码。有人喜欢新奇的语言功能…谢谢你的评论。正如您所说,我已经更新了我的版本,锁定了整个消费者功能。 #include <condition_variable> #include <

有一个使用
条件变量
的示例取自:


是的,您完全正确:在设置
done
之前,使用者线程可能(远程)不会开始运行。此外,生产者线程中的写入
done
和消费者线程中的读取产生竞争条件,并且行为未定义。你的版本也有同样的问题。在每个函数中围绕整个循环包装互斥锁。很抱歉,我没有精力编写正确的代码。

无论如何,这是可怕的代码。有人喜欢新奇的语言功能…谢谢你的评论。正如您所说,我已经更新了我的版本,锁定了整个
消费者
功能。
#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();
}
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);
});