【发布时间】: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