c/c++基于信号量+线程锁实现生产者消费者

  • Post author:
  • Post category:其他
#include<iostream>
#include<semaphore.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
using namespace std;

#define PRODUCER_NUM 3 //生产者线程数量
#define CONSUMER_NUM 1 //消费者线程数量

sem_t not_full;    //控制生产者可生产数量
sem_t not_empty;    //控制消费者可消费信号量
pthread_mutex_t mutex;

struct data
{
int front;
int rear;
int queue[6];
};

data buffer; //缓冲区为循环队列,如果存放5条数据,长度是6

void * producer(void * args)
{
	while(true)
	{

		sem_wait(&not_full);
		pthread_mutex_lock(&mutex);
		buffer.queue[buffer.rear]=rand()%100;
		cout <<"producer produce:"<<buffer.queue[buffer.rear]<<endl;
		buffer.rear=(buffer.rear+1)%6;
		pthread_mutex_unlock(&mutex);
		sem_post(&not_empty);		
	}
}
void * consumer(void * args)
{
	while(true)
	{
		
		sem_wait(&not_empty);
		pthread_mutex_lock(&mutex);
		cout <<"consumer consume:" <<buffer.queue[buffer.front]<<endl;
		sleep(1);
		buffer.queue[buffer.front]=0;
		buffer.front=(buffer.front+1)%6;		
		pthread_mutex_unlock(&mutex);
		sem_post(&not_full);		
	}	

}


int main()
{
	buffer.front=buffer.rear=0;
	pthread_mutex_init(&mutex,NULL);
	sem_init(&not_full,0,5);
	sem_init(&not_empty,0,0);

	pthread_t pid[PRODUCER_NUM+CONSUMER_NUM];
	for(int i=0;i<PRODUCER_NUM;i++)
	{
		pthread_create(&pid[i],NULL,producer,NULL);
	}
	for(int i=PRODUCER_NUM;i<PRODUCER_NUM+CONSUMER_NUM;i++)
	{
		pthread_create(&pid[i],NULL,consumer,NULL);
	}

	for(int i=0;i<PRODUCER_NUM+CONSUMER_NUM;i++)
	{
		pthread_join(pid[i],NULL);
	}

	sem_destroy(&not_full);
	sem_destroy(&not_empty);
	pthread_mutex_destroy(&mutex);		
	return 0;
}


版权声明:本文为u012094479原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。