【问题标题】:Producer/consumer, consumer thread never executed生产者/消费者,消费者线程从未执行
【发布时间】:2018-01-30 03:18:23
【问题描述】:

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

生产者线程每隔一秒不断地压栈,由互斥体保护。

消费者线程不断从堆栈中弹出。

出乎意料的行为是,生产者线程一直在运行,而消费者线程却没有机会出栈。

我该如何着手调查这个问题?非常感谢。

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

【问题讨论】:

    标签: c++ multithreading


    【解决方案1】:

    生产者在持有互斥锁的同时花费其睡眠时间。 这几乎没有给消费者锁定互斥锁的机会。

    如果你把 sleep 语句放在互斥保护区域之外,它会按预期工作..

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-24
      • 2017-02-01
      • 2012-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-10
      相关资源
      最近更新 更多