生产者/消费者,消费者线程从未执行过

Producer/consumer, consumer thread never executed

本文关键字:消费者 执行 线程 生产者      更新时间:2023-10-16

创建了一个具有生产者线程和使用者线程的程序。

生产者线程每秒连续推送到堆栈,该堆栈受互斥锁保护。

使用者线程不断从堆栈中弹出。

意外的行为是,生产者线程一直在运行,而使用者线程从来没有机会弹出堆栈。

如何继续调查此问题?非常感谢。

#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
  }