C++ 线程在调用 std::this_thread::sleep_for 时无法运行

问题描述

我测试了下面的代码,生产者线程无法运行,但删除std::this_thread::sleep_for(std::chrono::seconds(1));行, 它可以工作,为什么?

我知道消费者线程存在无限循环

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

using namespace std;

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

    std::thread consumer([&]() {
        pthread_setname_np("consumer");
        std::unique_lock<std::mutex> lock(m);
        while (!done) {
            while (!notified) { 
//                cond_var.wait(lock);
            }
            while (!produced_nums.empty()) {
                std::cout << "consuming " << produced_nums.front() << endl;
                produced_nums.pop();
            }
                notified = false;
        }
    });
                
    producer.join();
    consumer.join();
    
    std::cout << "end" << endl;
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)