Producers and consumers to realize the algorithm

Copyright: from: Jihome https://blog.csdn.net/jihome/article/details/88919159

Producers and consumers algorithm is a classical process synchronization algorithms, here is the use of C ++ simulation to achieve producer-consumer algorithm, to achieve synchronization between the pool and the exclusive access to the producer process and consumer process right.

Realization of ideas: Write a producer and consumer class with C ++, in which there is a constructor to initialize a pointer pointing to the product, product number and mutex mutex (mutual exclusion access count), followed by the producer and wrote consumers algorithm to note here is: can not be produced when the buffer is full, you can not consume the buffer is empty, there are tips here I have in operation. The main function is to call the producer-consumer loop, and then after each call state product output and the number of buffers.

Source:

#include <iostream>
#include <time.h>
#include <stdlib.h>
#define N 100	//产品数量
using namespace std;

/*生产者消费者类*/
class PandC{
private:
	int in,out;//指向有产品的下标
	int count;//缓冲区的产品数
	int buffer[N];//缓冲区
	int mutex;//互斥信号量
	int  empty,full;//判断缓冲区是否为空或者满
public:
	/*初始化,构造生产者消费者*/
	PandC(){
		in=0;out=0;count=0;
		empty=N;full=0;mutex=1;
		for(int i=0;i<N;i++)
			buffer[i]=0;
	}

	/*生产者生产*/
	void Producer(){
		if(empty==0){
			full=1;
			cout<<"产品已满,不能再生产"<<endl;
			return ;
		}
		Wait(empty);//empty--;
		
		buffer[out]=1;	//生产一个产品
		out=(out+1)%N;	//尾指针后移一位,构成循环队列

		cout<<"生产者生产了一个产品"<<endl;	

		/*对count互斥访问*/
		Wait(mutex);
		count++;
		Signal(mutex);
	}

	/*消费者消费*/
	void Consumer(){
		if(empty==N){
			cout<<"没有产品,不能消费"<<endl;
			return ;
		}
	
		buffer[in]=0;//消费一个产品
		in=(in+1)%N;//头指针后移一位,构成循环队列

		cout<<"消费者消费了一个产品"<<endl;
		
		/*对count互斥访问*/
		Wait(mutex);
		count--;
		Signal(mutex);

		if(empty<=N){
			full=0;
			Signal(empty);//empty++;
		}
	}
	
	/*显示现在缓冲区的情况*/
	void Display(){
		for(int i=0;i<N;i++)
			cout<<buffer[i];
		cout<<endl<<"一共有"<<count<<"个产品"<<endl<<endl;
	}
	
	void Wait(int &s){
		if(s<=0) return ;
		s--;
	}

	void Signal(int &s){
		s++;
	}

};

int main(){
	int i=0;
	srand(time(NULL));
	PandC x;

	/*随机执行生产者生产还是消费者消费*/
	do{
	if(rand()%100>80)//利用比例控制生产速度
		x.Producer();
	else
		x.Consumer();
	x.Display();
	i++;
	}while(i!=1000);

	return 0;
}

Producers and consumers to achieve a simple algorithm, using 0,1 expressed no product, or too abstract, and if they can use the progress bar in the form that would be better, but limited capacity, but the idea of ​​the algorithm to achieve them, still need learn and improve.

Guess you like

Origin blog.csdn.net/jihome/article/details/88919159