C++11/std::condition_variable - 生产者消费者模型

代码示例:


#include <iostream>             
#include <thread>         
#include <chrono>      
#include <mutex>
#include <deque>
#include <condition_variable>

std::deque<int> global_deque;
std::mutex global_mutex;
std::condition_variable global_ConditionVar;

// 生产者线程
void Producer()
{
	while (true)
	{
		// 休眠5毫秒
		std::this_thread::sleep_for(std::chrono::milliseconds(5));

		std::unique_lock<std::mutex> lock(global_mutex);
		global_deque.push_front(1);
		std::cout << "生产者生产了数据" << std::endl;
		global_ConditionVar.notify_all();
	}
}

// 消费者线程
void Consumer()
{
	while (true)
	{
		std::unique_lock<std::mutex> lock(global_mutex);

		// 当队列为空时返回false,则一直阻塞在这一行
		global_ConditionVar.wait(lock, [] {return !global_deque.empty(); });
		global_deque.pop_back();

		std::cout << "消费者消费了数据" << std::endl;
		global_ConditionVar.notify_all();
	}
}

int main()
{

	std::thread consumer_Thread(Consumer);
	//std::thread consumer_Thread1(Consumer);

	std::thread producer_Thread(Producer);

	consumer_Thread.join();
	//consumer_Thread1.join();
	producer_Thread.join();
	

	getchar();
	return 0;
}

在这里插入图片描述
有兴趣可以访问我的个站:www.stubbornhuang.com

发布了176 篇原创文章 · 获赞 295 · 访问量 71万+

猜你喜欢

转载自blog.csdn.net/HW140701/article/details/105251359