C++ 11 生产者消费者模式

单生产者单消费者模式,假设生产者每次产量等于与消费者每次消耗量
C++ 11 使用unique_lock 和 condition_variable 实现

//#include "stdafx.h"
#include <iostream>
#include <vector>
#include <thread>
#include <mutex>
#include <condition_variable>

using namespace std;

//单生产者单消费者模式,假设生产者每次产量等于与消费者每次消耗量
class Repository {
public:
	Repository(const int sz = 9) : circularBuffer(sz) {} //仓库容量大小为sz
	Repository(const Repository& other) = delete;
	Repository operator=(const Repository& other) = delete;
	~Repository() {}

	void producer() {
		cout << " producer thread id:" << std::this_thread::get_id() << endl;
		for (int i = 0; i < capacity; ++i) {
			std::unique_lock<std::mutex> smartLock(mtx);
			//可用量小于仓库容量,尝试获取锁,然后生产
			buffNotFull.wait(smartLock, [this] {return bufferd < circularBuffer.size(); });
			circularBuffer[proPosnMark] = i;
			proPosnMark = (proPosnMark + 1) % circularBuffer.size();
			++bufferd;
			cout << "producer input:" << i << endl;
			smartLock.unlock(); //解锁
			buffNotEmpty.notify_all(); //通知消费者
		}
		return;
	}

	void consumer() {
		cout << "consumer thread id:" << std::this_thread::get_id() << endl;
		for (int i = 0; i < capacity; ++i) {
			std::unique_lock<std::mutex> smartLock(mtx);
			buffNotEmpty.wait(smartLock, [this] {return bufferd > 0;}); 
			int val = circularBuffer[conPosnMark];
			cout << " consumer delete:" << val << endl;
			conPosnMark = (conPosnMark + 1) % circularBuffer.size();
			--bufferd;
			smartLock.unlock();
			buffNotFull.notify_all(); 
		}
		return;
	}

private:
	std::vector<int> circularBuffer; //环形仓库
	size_t bufferd = 0; //仓库内可用产品
	size_t proPosnMark = 0; //生产者位置标记
	size_t conPosnMark = 0; //消费者位置标记
	int capacity = 100; //生产总量
	std::mutex mtx;
	std::condition_variable buffNotEmpty; //仓库未空
	std::condition_variable buffNotFull;  //仓库未满

};


int main(int argc, char *argv[])
{
	cout << "main thread id:" << std::this_thread::get_id() << endl;

	Repository mRep;
	std::vector<std::thread> vThreads;
	
	vThreads.push_back(std::thread(&Repository::producer, &mRep));
	vThreads.push_back(std::thread(&Repository::consumer, &mRep));

	for (auto &elem : vThreads) {
		elem.join();
	}

	system("pause");
	return 0;
}

//关于condition_variable
//condition_variable.wait()第二参数(谓词)。
//不带谓词,线程直接被block,等待被唤醒,被唤醒后,尝试获取锁。
//带有谓词,返回false,解锁, 线程被block,等待被唤醒,返回ture, 尝试获取锁,获取后,线程往下走。

enjoy;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值