先进先出生产者消费者模式实现

以下代码未经编译调试,可能编译不过。只是大概写了下实现。

#include <iostream>
#include <queue>

using namespace std;

class CBuffer
{
private: 
	mutex m_mutex;
	condition_variable_any cond_put;
	condition_variable_any cond_get;
	queue<int> q_que;
	int n_wait_read;
	int n_capacity;
	bool IsFull()
	{
		return (n_wait_read == n_capacity);
	}
	
	bool IsEmpty()
	{
		return (n_wait_read == 0);
	}
	
public:
	CBuffer(int n_size)
		: n_wait_read(0)
		: n_capacity(n_size)
	{
			
	}
	
	void put(int x)
	{
		{
			auto lck = make_unique_lock(m_mutex);
			cond_put.wait(lck, [&]()->bool{ return !IsFull(); });
			q_que.push(x);
			n_wait_read++;
		}
		
		cond_get.notify_one();
	}
	
	void get(int *x)
	{
		{
			auto lck = make_unique_lock(m_mutex);
			cond_get.wait(lck, [&]()->bool{ return !IsEmpty(); });
			n_wait_read--;
			*x = q_que.front();
			q_que.pop();
		}
		
		cond_put.notify_one();		
	}
}

CBuffer buf(5);

void Producer(int n)
{
	for (int i = 0; i < n; i++)
	{
		cout << "put" << i << endl;
		buf.put(i);
	}
}

void Consumer(int n)
{
	int x;
	for( int i = 0; i < n; i++)
	{
		buf.get(&x);
		cout << "get" << x << endl;
	}
}

int main()
{ 
	thread_group tg;
	
	tg.create_thread(bind(Producer, 20));
	tg.create_thread(bind(Consumer, 10));
	tg.create_thread(bind(Consumer, 10));

	tg.join_all();
	
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值