#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(¬_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(¬_empty);
}
}
void * consumer(void * args)
{
while(true)
{
sem_wait(¬_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(¬_full);
}
}
int main()
{
buffer.front=buffer.rear=0;
pthread_mutex_init(&mutex,NULL);
sem_init(¬_full,0,5);
sem_init(¬_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(¬_full);
sem_destroy(¬_empty);
pthread_mutex_destroy(&mutex);
return 0;
}
版权声明:本文为u012094479原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。