pthread 实现生产者消费者问题

时间:2023-01-22 21:48:39
经典的生产者消费者问题,在这里用信号量和互斥量来实现生产和消费者模型
 
#include<cstdlib>
#include<cstdio>
#include<unistd.h>
#include<pthread.h>
#include<semaphore.h>
int t = 0;
sem_t empty,full;
pthread_mutex_t mutex;
void* producer(void* arg){
int* time=(int*) arg;
while(true){
sem_wait(&empty);
pthread_mutex_lock(&mutex);
//add
t++;
printf("producer add 1 to %d\n", t);
pthread_mutex_unlock(&mutex);
sem_post(&full);
sleep(*time);
}
} void* customer(void* arg){ while(true){
sem_wait(&full);
pthread_mutex_lock(&mutex);
//delete
t--;
printf("customer delete 1 to %d\n", t);
pthread_mutex_unlock(&mutex);
sem_post(&empty);
sleep(4);
}
} int main(){
pthread_t pthread_producer,pthread_producer_2;
pthread_t pthread_customer;
pthread_mutex_init(&mutex,NULL);
sem_init(&full,0,0);
sem_init(&empty,0,10);
int a = 2;
int b = 3;
pthread_create(&pthread_producer,NULL,producer,&a);
pthread_create(&pthread_producer_2,NULL,producer,&b);
pthread_create(&pthread_customer,NULL,customer,NULL);
pthread_join(pthread_customer,NULL);
pthread_join(pthread_producer,NULL);
pthread_join(pthread_producer_2,NULL);
return 0;
}