生产者消费者模型

 参考博客

# include<iostream>
# include<thread>
# include<vector>
# include<mutex>
# include<condition_variable>
# include<queue>
#include <windows.h>

using namespace std;

//生产者数量
# define PRODUCT_SIZE 20
//消费者数量
# define CUSTOMER_SIZE 1
//最大产品数量
#define MAX_SIZE 10
//互斥锁
mutex mut;
//条件变量
condition_variable con;
//队列,模拟缓冲区
queue<int> que;


//当缓冲区满了,生产者等待,不能继续生产
//当缓冲区空了,消费者等待,不能继续消费

void Producter()
{
	static int data = 0;
	while (true)
	{
		Sleep(1000);
		std::unique_lock <std::mutex> lck(mut);
		while (que.size() > MAX_SIZE)
		{
			con.wait(lck);// wait for signal  如果满了则等待
		}
		data %= 20;
		que.push(data);
		cout <<"线程ID:" <<this_thread::get_id() << "\t生产了产品:" << data << endl;
		con.notify_all();//wake up all waiters  如果不满,则唤醒所有等待的线程
		data++;
	}
}
void Customer()
{
	while (true)
	{
		std::unique_lock <std::mutex> lck(mut);
		while (que.empty())
		{
			con.wait(lck);	//如果空了则等待
		}
		cout << "线程ID:" << this_thread::get_id() << "\t消费了产品:" << que.front() << endl;
		que.pop();
		con.notify_all();  //如果不空则唤起所有等待的线程
	}
}
int main()
{
	vector<thread> threadPoll;
	//创建生产者和消费者
	for (int i = 0; i < PRODUCT_SIZE; ++i)
	{
		threadPoll.push_back(thread(Producter));
	}

	for (int i = 0; i < CUSTOMER_SIZE; ++i)
	{
		threadPoll.push_back(thread(Customer));
	}

	//21个线程
	for (int i = 0; i < PRODUCT_SIZE + CUSTOMER_SIZE; ++i)
	{
		threadPoll[i].join();
	}

	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

aspiretop

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值