#include<list>
#include<stdio.h>
#include<pthread.h>
#include <semaphore.h>
#include <iostream>
using namespace std;
sem_t mutex;
sem_t fillCount;
sem_t emptyCount;
list <int> l;
int x;
pthread_t thread[2];
void *producer(void *);
void *consumer(void *);
int main()
{
sem_init(&mutex,0,1);
sem_init(&fillCount,0,0);
sem_init(&emptyCount,0,3);
void *p;
pthread_create(&thread[0],NULL,producer,NULL);
pthread_create(&thread[1],NULL,consumer,NULL);
pthread_join(thread[0],&p);
pthread_join(thread[1],&p);
}
void *producer(void *) {
int i=0;
while (true) {
sem_wait(&emptyCount);
sem_wait(&mutex);//emptycount和mutex的顺序不能对调
//printf("producer done\n");
sleep(1);
l.push_back(i);
i++;
sem_post(&mutex);
sem_post(&fillCount);
//printf("prove\n");
}
return NULL;
}
void *consumer(void *) {
while (true) {
sem_wait(&fillCount);
sem_wait(&mutex);
x=l.front();
l.pop_front();
printf("%d\n",x);
//printf("consumer done\n");
sleep(1);
sem_post(&mutex);
sem_post(&emptyCount);
// printf("cous\n");
}
return NULL;
}
生产者与消费者
最新推荐文章于 2024-05-01 23:33:30 发布