CPP线程:生产者与消费者的问题

#include <iostream>
#include <thread>
#include<condition_variable>
#include <mutex>
#include<ctime>
#include <array>
#include <vector>
using namespace std;
mutex m;
condition_variable full,empty;
bool flag = true;//标志 消费完了就退出
vector<int>myint(10);//开辟10个元素
int num = 10;

void put(int num)//生产
{
	for (int i = 0; i < num; i++)
	{
		unique_lock<mutex>lk(m);
		while (10<=myint.size())
		{
			empty.wait(lk);//满了就一直等待
		}
		myint.push_back(i);//插入数据
		cout << "生产:" <<i<< endl;
		full.notify_all();
	}
	this_thread::sleep_for(chrono::seconds(3));
	flag = false;
}
void take()//消费
{
	while (flag)
	{
		unique_lock<mutex>lk(m);
		while (0==myint.size())
		{
			full.wait(lk);//等待
		}
		if (flag)//消费
		{
			cout << myint[myint.size() - 1] <<"	ID:"<<this_thread::get_id()<< endl;
			myint.pop_back();
			empty.notify_all();
		}
	}
}
//多个生产者  对  多个消费者
void main()
{
	//创建消费者
	thread t1(take);
	thread t2(take);
	thread t3(take);

	thread s1(put, 10);
	thread s2(put, 10);
	t1.join();
	t2.join();
	t3.join();
	cin.get();
}

//单个生产者 与  单个消费者
void main()
{
	//创建消费者
	thread t1(take);
	thread t2(take);
	thread t3(take);
	thread t4(take);

	put(10);//生产
	t1.join();
	t2.join();
	t3.join();
	t4.join();
	cin.get();
}<img src="https://img-blog.youkuaiyun.com/20150822013207296?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />

更多资料 · 微信公众号搜索【CTO Plus】关注后,获取更多,我们一起学习交流。

关于公众号的描述访问如下链接


关于Articulate“做一个知识和技术的搬运工。做一个终身学习的爱好者。做一个有深度和广度的技术圈。”一直以来都想把专业领域的技https://mp.weixin.qq.com/s/0yqGBPbOI6QxHqK17WxU8Q

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

SteveRocket

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

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

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

打赏作者

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

抵扣说明:

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

余额充值