生产者消费者

  1 #include <stdio.h>
  2 #include <string.h>
  3 #include <stdlib.h>
  4 #include <unistd.h>
  5 #define _GNU_SOURCE
  6 #include <pthread.h>
  7 enum bool { FALSE = 0,TRUE =1};
  8 enum bool slave_can_print = TRUE;
  9 enum bool main_can_print = FALSE;
 10 
 11 #define  NUMBER_PRODUCER  5
 12 #define  NUMBER_CONSUMER  3
 13 const int max_capacity = 10;
 14 int capacity = 10 ;
 15 
 16 
 17 pthread_cond_t  cond_prod = PTHREAD_COND_INITIALIZER;
 18 pthread_cond_t  cond_cons = PTHREAD_COND_INITIALIZER;
 19 pthread_mutex_t mutex_pool = PTHREAD_MUTEX_INITIALIZER;
 20 
 21 
 22 void* thread_prod(void* arg);
 23 void* thread_cons(void* arg);
 24 int get_interval(void);
 25 
 26 int main(int argc, char* argv[])
 27 {
 28     int ret;
 29     int i;
 30     pthread_t prod[NUMBER_PRODUCER];
 31     pthread_t cons[NUMBER_CONSUMER];
 32 
 33     for( i = 0; i < NUMBER_PRODUCER; i++)
 34     {
 35         ret = pthread_create(&prod[i],NULL,thread_prod,(void*)i);
 36         if( ret != 0 )
 37         {
 38             strerror(ret);
 39         }
 40     }
 41     for( i = 0; i < NUMBER_CONSUMER; i++)
 42     {
 43         ret = pthread_create(&cons[i],NULL,thread_cons,(void*)i);
 44         if( ret != 0 )
 45         {
 46             strerror(ret);
 47         }
 48     }
 49 
 50     pthread_exit(NULL);
 51 
 52 }
 53 void* thread_prod(void* arg)
 54 {
 55     int id = (int)arg;
 56     int interval;
 57     while(1)
 58     {
 59         pthread_mutex_lock(&mutex_pool);
 60         if(capacity < max_capacity)
 61         {
 62             capacity ++;
 63             printf("producer %d  capacity is %d\n",id,capacity);
 64             pthread_cond_signal(&cond_cons);
 65             interval = get_interval();
 66             sleep(interval);
 67         }
 68         else
 69         {
 70             pthread_cond_wait(&cond_prod,&mutex_pool);
 71         }
 72         pthread_mutex_unlock(&mutex_pool);
 73     }
 74     return NULL;
 75 }
 76 void* thread_cons(void* arg)
 77 {
 78     int id = (int)arg;
 79     int interval;
 80     while(1)
 81     {
 82         pthread_mutex_lock(&mutex_pool);
 83         if(capacity > 0 )
 84         {
 85             capacity --;
 86             printf("consumer %d  capacity is %d\n",id,capacity);
 87             pthread_cond_signal(&cond_prod);
 88             interval = get_interval();
 89             //pthread_yield();
 90             sleep(interval);
 91         }
 92         else
 93         {
 94             pthread_cond_wait(&cond_cons,&mutex_pool);
 95         }
 96         pthread_mutex_unlock(&mutex_pool);
 97     }
 98 
 99     return NULL;
100 }
101 
102 int get_interval(void)
103 {
104     int val;
105     srand(time(NULL));
106     val =  rand() % 3;
107     return val;
108 }

 

posted @ 2017-08-25 16:37  小鱼儿403  阅读(132)  评论(0编辑  收藏  举报