生產者消費者問題-C++程式碼實現

xyfyy發表於2024-08-19

生產者消費者問題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;
}

相關文章