简体   繁体   English

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

[英]Producer/consumer, consumer thread never executed

Created a program having a producer thread and a consumer thread. 创建了一个具有生产者线程和消费者线程的程序。

The producer thread continuously pushes to a stack every one second, which is protected by a mutex. 生产者线程每隔一秒连续推送到一个堆栈,受到互斥锁的保护。

The consumer thread continuously pops from the stack. 消费者线程不断从堆栈中弹出。

The unexpected behavior is that, the producer thread is constantly running, while the consumer thread never gets a chance to pop the stack. 意外的行为是,生产者线程一直在运行,而消费者线程永远不会有机会弹出堆栈。

How could I proceed to investigate this problem? 我怎么能继续调查这个问题? Many thanks. 非常感谢。

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

The producer is spending its sleeping time while holding the mutex. 制作人在持有互斥锁时花费其休眠时间。 This hardly gives the consumer a chance to lock the mutex. 这几乎不能让消费者有机会锁定互斥锁。

If you put the sleep statement outside the mutex protected area, it will work as expected.. 如果将sleep语句放在互斥保护区域之外,它将按预期工作。

void producer(const int id)
{
  while(1)
  {
    ....
    mtx.unlock();
    std::this_thread::sleep_for(std::chrono::seconds(1)); // below the unlock operation
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM