生产者消费者问题-C++代码实现

生产者消费者问题C++代码

本文主要记录面试中手撕代码环节比较经常考察的生产者消费者问题,方便后续巩固和查看

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>
#include <functional>
using namespace std;

class ProduceAndConsumer {
public:
	ProduceAndConsumer() {
		producer = new std::thread(std::bind(&ProduceAndConsumer::produce, this));
		consumer = new std::thread(std::bind(&ProduceAndConsumer::consume, this));
	}
	~ProduceAndConsumer() {
		if (producer->joinable()) {
			producer->join();	// 线程阻塞,直至完成
		}
		if (consumer->joinable()) {
			consumer->join();	// 线程阻塞,直至完成
		}
		std::cout << "progress finish" << std::endl;
	}

	void produce() {
		int produce_count = 0;
		while (!isNotFinishProduce) {
			std::unique_lock<std::mutex> lock_guard(mu);
			while (q.size() >= q_max_size) {
				cond.wait(lock_guard);
			}
			int conduct = num++;
			q.push(conduct);
			produce_count++;
			std::cout << "product conduct, num = " << conduct << std::endl;
			if (produce_count > maxConductNum) {
				isNotFinishProduce = true;
			}
			lock_guard.unlock();
			cond.notify_all();
		}
	}

	void consume() {
		int consume_count = 0;
		while (!isNotFinishConsumer) {
			std::unique_lock<std::mutex> lock_guard(mu);
			while (q.empty()) {
				cond.wait(lock_guard);
			}
			int x = q.front();
			q.pop();
			std::cout << "consumer conduct: num = " << x << std::endl;
			consume_count++;
			if (consume_count > maxConductNum) {
				isNotFinishConsumer = true;
			}
			lock_guard.unlock();
			cond.notify_all();
		}
	}

private:
	std::thread* producer;
	std::thread* consumer;
	std::condition_variable cond;
	std::mutex mu;
	queue<int> q;
	int q_max_size = 100;
	bool isNotFinishProduce = false;
	bool isNotFinishConsumer = false;
	int maxConductNum = 1000;
	int num = 0;
};

int main() {
	ProduceAndConsumer* p = new ProduceAndConsumer();
	delete p;
	return 0;
}
posted @   xyfyy  阅读(101)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示