生产者/消费者,消费者线程从未执行过
Producer/consumer, consumer thread never executed
创建了一个具有生产者线程和使用者线程的程序。
生产者线程每秒连续推送到堆栈,该堆栈受互斥锁保护。
使用者线程不断从堆栈中弹出。
意外的行为是,生产者线程一直在运行,而使用者线程从来没有机会弹出堆栈。
如何继续调查此问题?非常感谢。
#include <stack>
#include <chrono>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <iostream>
std::mutex mtx;
std::stack<int> the_stack;
void producer(const int id)
{
while(1)
{
mtx.lock();
the_stack.push(0);
std::cout << "Producer " << id << " push" << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
mtx.unlock();
}
}//producer
void consumer(const int id)
{
while(1)
{
mtx.lock();
if (!the_stack.empty())
{
std::cout << "Consumer " << id << " pop" << std::endl;
the_stack.pop();
}
mtx.unlock();
}
}//consumer
int main()
{
std::thread thread_0(producer, 0);
std::thread consum_0(consumer, 0);
thread_0.join();
consum_0.join();
return 0;
}//main;
生产者在保持互斥锁的同时度过了睡眠时间。这几乎不会给消费者锁定互斥锁的机会。
如果将 sleep 语句放在互斥锁保护区域之外,它将按预期工作。
void producer(const int id)
{
while(1)
{
....
mtx.unlock();
std::this_thread::sleep_for(std::chrono::seconds(1)); // below the unlock operation
}
相关文章:
- 在执行其他功能的同时播放动画(LED矩阵和Arduino/ESP8266)
- C++,系统无法执行指定的程序
- 使用C++中的模板和运算符重载执行矩阵运算
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 执行函数时导致崩溃的变量
- 无论条件是否为true,if总是在c++中执行
- 当函数模板参数是具有默认参数的类模板时,函数模板参数的推导如何执行
- 在C++中对T*类型执行std::move的意外行为
- 使用QProcess执行命令,并将结果存储在QStringList中
- 如何在没有信号的情况下从C++执行QML插槽
- 如何确认我的constexpr表达式实际上已经在编译时执行
- C++17中的并行执行策略
- QML按钮点击功能执行顺序
- 程序在执行程序的其余部分之前退出
- 为什么catch中的代码没有被执行
- C++从其他 constexpr 创建 lambda 不能按顺序执行 Constexpr
- 将执行、作业和WinAPI相乘
- 对字符数组中的元素执行逐位操作
- 为什么g++在未执行的代码处标记强制转换错误
- 生产者/消费者,消费者线程从未执行过