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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章