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

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

  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

 

你可能感兴趣的:(c++)