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
    评论
当然,这里是一个简单的用C++编写的消费者生产者模式的例子: ```cpp #include <iostream> #include <queue> #include <thread> #include <mutex> #include <condition_variable> std::queue<int> buffer; const int bufferSize = 10; std::mutex mtx; std::condition_variable bufferNotEmpty, bufferNotFull; void producer() { for (int i = 1; i <= 20; ++i) { std::unique_lock<std::mutex> lock(mtx); bufferNotFull.wait(lock, [] { return buffer.size() < bufferSize; }); buffer.push(i); std::cout << "Producer produced item: " << i << std::endl; lock.unlock(); bufferNotEmpty.notify_one(); } } void consumer() { for (int i = 1; i <= 20; ++i) { std::unique_lock<std::mutex> lock(mtx); bufferNotEmpty.wait(lock, [] { return !buffer.empty(); }); int item = buffer.front(); buffer.pop(); std::cout << "Consumer consumed item: " << item << std::endl; lock.unlock(); bufferNotFull.notify_one(); } } int main() { std::thread producerThread(producer); std::thread consumerThread(consumer); producerThread.join(); consumerThread.join(); return 0; } ``` 在这个例子中,我们使用`std::queue`作为缓冲区,`std::mutex`来保护共享资源的访问,`std::condition_variable`用于线程间的同步通信。 生产者函数`producer()`负责将数字1到20依次放入缓冲区中,每次放入一个数字后,会通知消费者线程。 消费者函数`consumer()`负责从缓冲区中取出数字并消费,每次消费一个数字后,会通知生产者线程。 在`main()`函数中,我们创建了一个生产者线程和一个消费者线程,并等待它们的执行完毕。 请注意,这只是一个简单的示例,实际使用中可能需要更复杂的逻辑来处理并发和同步。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值