#include<stdio.h>#include<unistd.h>#include<stdlib.h>#include<pthread.h>int count =0;
pthread_mutex_t mutex;
pthread_cond_t cond;void*custom(void*arg){while(1){pthread_mutex_lock(&mutex);//整个消费过程加锁if( count ==0){//判断是否有产品,没有则阻塞等待生产者生产产品并发出signalprintf("count is 0\n");pthread_cond_wait(&cond,&mutex);}
count--;//产品减一printf("custom id is %lu, count is %d\n",pthread_self(), count);pthread_mutex_unlock(&mutex);sleep(1);}pthread_exit(0);}void*produce(void*arg){while(1){pthread_mutex_lock(&mutex);//生产过程也要加锁if( count >=10){//判断产品是否累积过多printf("produce is too more\n");pthread_mutex_unlock(&mutex);//解锁等待并且跳过循环sleep(1);continue;}
count++;//产品加一printf("produce id is %lu, count is %d\n",pthread_self(), count);pthread_cond_signal(&cond);//有产品就发送信号给消费者pthread_mutex_unlock(&mutex);sleep(1);}pthread_exit(0);}intmain(){
pthread_t custom1, custom2, produce1, produce2, produce3;pthread_create(&custom1,NULL, custom,NULL);//创建消费者和生产者pthread_create(&custom2,NULL, custom,NULL);sleep(3);pthread_create(&produce1,NULL, produce,NULL);pthread_create(&produce2,NULL, produce,NULL);pthread_create(&produce3,NULL, produce,NULL);pthread_join(custom1,NULL);//等待线程结束pthread_join(custom2,NULL);pthread_join(produce1,NULL);pthread_join(produce2,NULL);pthread_join(produce3,NULL);return0;}