生产者消费者模式

#include <queue>
#include <string>
#include <mutex>
#include <thread>
#include <iostream>
class CBuffer
{
public:
	CBuffer() {}
	~CBuffer() {}

	static CBuffer* GetBuffer()
	{
		if (!m_buffer){
			m_buffer = new CBuffer();
		}
		return m_buffer;
	}

	int GetSize()
	{
		std::lock_guard<std::mutex> locker(m_mutex);
		return m_queue_list.size();
	}

	bool IsEmpty()
	{
		std::lock_guard<std::mutex> locker(m_mutex);
		return m_queue_list.empty();
	}

	bool IsFull()
	{
		std::lock_guard<std::mutex> locker(m_mutex);
		return m_queue_list.size() == BUFFER_SIZE;
	}

	bool Push(const std::string& str)
	{
		if (!IsFull()) {
			std::lock_guard<std::mutex> locker(m_mutex);
			m_queue_list.push(str);
			return true;
		}
		return false;
	}

	bool Pop(std::string& str)
	{
		if (!IsEmpty()) {
			std::lock_guard<std::mutex> locker(m_mutex);
			str = m_queue_list.front();
			m_queue_list.pop();
			return true;
		}
		return false;
	}

private:
	std::mutex m_mutex;
	std::queue<std::string> m_queue_list;
	static CBuffer* m_buffer;
	static int BUFFER_SIZE;
};
CBuffer* CBuffer::m_buffer = nullptr;
int CBuffer::BUFFER_SIZE = 100;

std::shared_ptr<CBuffer> gBuffer(CBuffer::GetBuffer());
class Producer
{
public:
	bool Produce(const std::string& s)
	{
		return gBuffer->Push(s);
	}
};

class Consumer
{
public:
	bool Consume(std::string& s)
	{
		return gBuffer->Pop(s);
	}
};

bool bThreadStart = true;

void thread1()
{
	Producer producer;
	while (bThreadStart)
	{
		std::string s = std::to_string( rand() % 100 + 1);
		if (producer.Produce(s)) {
			std::cout << "produce s:" << s << std::endl;
		} 
		std::this_thread::sleep_for(std::chrono::seconds(1));
	}
}

void thread2()
{
	Consumer consumer;
	while (bThreadStart)
	{
		std::string s;
		if (consumer.Consume(s)) {
			std::cout << "consume s:" << s << std::endl;
		} 
		std::this_thread::sleep_for(std::chrono::seconds(1));
	}
}

int main()
{
	srand(time(nullptr));
	std::thread t1(thread1);
	std::thread t2(thread2);

	t1.join();
	t2.join();

	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值