信号量实现的生产者与消费者模型

信号量实现的生产者与消费者模型

  1 #include <stdio.h>
  2 #include <unistd.h>
  3 #include <pthread.h>
  4 #include <semaphore.h>
  5 #include <stdlib.h>
  6 
  7 
  8 sem_t blank, xfull;
  9 #define _SEM_CNT_ 5
 10 
 11 int queue[_SEM_CNT_];//模拟饼框,容器
 12 int beginnum = 100;
 13 
 14 void* thr_producer(void* arg)
 15 {
 16     int i = 0;
 17     while(1){
 18         sem_wait(&blank);//申请资源blank--
 19         printf("--%s---self--%lu---num--%d\n",__FUNCTION__,pthread_self(),beginnum);
 20         queue[(i++)%_SEM_CNT_] = beginnum++;
 21         sem_post(&xfull);//xfull++
 22         sleep(rand()%3);
 23     }
 24     return NULL;
 25 }
 26 
 27 void* thr_customer(void* arg)
 28 {
 29     int i = 0;
 30     int num = 0;
 31     while(1){
 32         sem_wait(&xfull);//xfull--
 33         num = queue[(i++)%_SEM_CNT_];
 34         printf("--%s---self--%lu---num--%d\n",__FUNCTION__,pthread_self(),num);
 35         sem_post(&blank);//blank++
 36         sleep(rand()%3);
 37     }
 38 
 39     return NULL;
 40 }
 41int main(){
 43     sem_init(&blank,0,_SEM_CNT_);
 44     sem_init(&xfull,0,0); //消费者初始化默认没有产品
 45 
 46     pthread_t tid[2];
 47 
 48     pthread_create(&tid[0],NULL,thr_producer,NULL);
 49     pthread_create(&tid[1],NULL,thr_customer,NULL);
 50 
 51     pthread_join(tid[0],NULL);
 52     pthread_join(tid[1],NULL);
 53 
 54     sem_destroy(&blank);
 55     sem_destroy(&xfull);
 56     return 0;
 57 }
                                                                                             57,1          Bot

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值