生产者-消费者信号量问题

#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);
	}
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值