#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <ctype.h>
#include <semaphore.h>
#define N 10
struct Product{
int value;
int ID;
}buffer[N];
sem_t mutex;
sem_t empty;
sem_t full;
int in=0,out=0;
int productID=0;
#define random(x) (rand()%x)
void* produce(int threadname);
void* consume(int threadname);
int main(){
sem_init(&mutex,0,1);
sem_init(&empty,0,N);
sem_init(&full,0,0);
pthread_t tid[5];
pthread_attr_t attr[5];
int i=0,j=0,k=0;
for(i=0;i<3;i++){
//pthread_attr_init(&attr[i]);
pthread_create(&tid[i],NULL,produce,i);
}
for(j=0;j<2;j++){
/pthre/ad_attr_init(&attr[j]);
pthread_create(&tid[j+3],NULL,consume,j);
}
for(k=0;k<5;k++){
pthread_join(tid[k],NULL);
}
}
void* produce(int threadname){
while(1){
sem_wait(&empty);
sem_wait(&mutex);
struct Product p;
productID++;
p.ID=productID;
p.value=random(100);
buffer[in]=p;
in=(in+1)%N;
printf("producer%d produce a product:(1)ID--%d,(2)Value--%d\n",threadname,p.ID,p.value);
sem_post(&mutex);
sem_post(&full);
sleep(2);
}
}
void* consume(int threadname){
while(1){
sem_wait(&full);
sem_wait(&mutex);
struct Product p=buffer[out];
out=(out+1)%N;
printf("consumer%d consume a product:(1)ID--%d,(2)Value--%d\n",threadname,p.ID,p.value);
sem_post(&mutex);
sem_post(&empty);
sleep(3);
}
}
生产者-消费者信号量问题
最新推荐文章于 2023-05-19 21:21:01 发布