关闭

多线程编程之PV操作示例代码

标签: c++生产者消费者pv
74人阅读 评论(0) 收藏 举报
分类:

近期使用了下操作系统的PV操作实现了数据缓存功能的程序,记录下来供大家参考。

程序功能是生产者消费者模型,写数据线程产生数据,数据达到buffer上限时,通知消费者取数据,buffer的size可以动态设定 数据类型为double


生产者消费者模型 DataBuffer.hpp:

#include <iostream>
#include <mutex>
#include <condition_variable>
#include <vector>

class DataBuffer{
public:
	DataBuffer(int size):size(size){}
	~DataBuffer(){}
	void produce(std::vector<double> dataset){
		std::unique_lock<std::mutex> locker(m_mutex);
		if (databuf.size() == size){
			std::cout<<"DataBuffer wait for data buffer clear";
			empty.wait(locker);
		}
		//produce start
		databuf.push_back(dataset);
		//produce end

		if(databuf.size() == size){
			full.notify_one();
		}
	}

	void consume(std::vector<std::vector<double>> &output){
		std::unique_lock<std::mutex> locker(m_mutex);
		if (databuf.size() < size){
			full.wait(locker);
		}

		//consume begin
		output.insert(output.begin(), databuf.begin(), databuf.end());
		databuf.clear();
		//consume end

		empty.notify_one();
	}

	void reset(){
		std::unique_lock<std::mutex> locker(m_mutex);
		databuf.clear();
	}


private:
	std::mutex m_mutex;
	std::condition_variable empty, full;

	const unsigned int size;
	std::vector<std::vector<double>> databuf;
};

测试程序 DataBuffer.cpp:

#include "DataBuffer.hpp"
#include <thread>

int main(){
	DataBuffer databuffer(8);
	std::thread producer([&]()
	{
		std::vector<double> dataset;
		dataset.push_back(1);
		while(1){
			std::this_thread::sleep_for (std::chrono::milliseconds (100));
			databuffer.produce(dataset);
			std::cout<<"producer Thread+++"<<std::endl;
		}
	});

	std::thread consumer([&]()
	{
		std::vector<std::vector<double>> output;
		while(1){
			databuffer.consume(output);
			std::cout<<"consumer Thread-----"<<std::endl;
		}
	});

	producer.join();
	consumer.join();
	std::cout<<"Main Thread"<<std::endl;

	return 0;
}

运行效果:

pv# g++ -std=c++11 DataBuffer.cpp -o DataBuffer.out -lpthread
pv# ./DataBuffer.out
producer Thread+++
producer Thread+++
producer Thread+++
producer Thread+++
producer Thread+++
producer Thread+++
producer Thread+++
producer Thread+++
consumer Thread-----
producer Thread+++
producer Thread+++
producer Thread+++
producer Thread+++
producer Thread+++
producer Thread+++
producer Thread+++
producer Thread+++
consumer Thread-----
producer Thread+++



0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:4801次
    • 积分:195
    • 等级:
    • 排名:千里之外
    • 原创:15篇
    • 转载:0篇
    • 译文:0篇
    • 评论:7条
    文章分类
    最新评论