生成者与消费者

来源:互联网 发布:剑侠情缘3网游mac 编辑:程序博客网 时间:2024/06/08 06:46
/****************************************************************************************************************
面试必备  

生产者:判断能否生产,若能便进入生产延时,生产完后准备进仓库,首先要获得锁,如果有
锁进入仓库加锁,然后产品数增加一,最后出库解锁  消费者:判断能否消费,若能便准备进入仓库,
如果有锁进入仓库取走产品,此时生产者便多产  了一个生空间,然后消费者进入消费延时
****************************************************************************************************************/



#include <pthread.h>#include <stdio.h>#include <semaphore.h>#define INIT 3#define TOTAL 10pthread_mutex_t mutex;sem_t sem_pro, sem_cus;int total_num = INIT;//库中产品数量//flag = 1:增加//flag = 0:减少void add_sub_num(int flag){if(1 == flag){pthread_mutex_lock(&mutex);//生产者进库加锁total_num++;printf("push in total = %d\n", total_num);pthread_mutex_unlock(&mutex);//生产者出库解锁}else if(0 == flag){pthread_mutex_lock(&mutex);total_num--;printf("push out total = %d\n", total_num);pthread_mutex_unlock(&mutex);}}void *pro(void *arg){while(1){sem_wait(&sem_pro);//判断能否生产usleep(500*1000);//生产延时的概念add_sub_num(1);//产品入库sem_post(&sem_cus);//消费者可以多消费一个产品}return NULL;}void *cus(void *arg){while(1){sem_wait(&sem_cus);//判断消费者能否消费add_sub_num(0);//出库//关键:消费者一旦出库,生成者就能生成了sem_post(&sem_pro);//生产者可以多消费一个产品usleep(800*1000);//消费延时}return NULL;}void pro_cus(void){pthread_t tid_pro, tid_cus;int ret;pthread_mutex_init(&mutex, NULL);sem_init(&sem_pro, 0, TOTAL - INIT);sem_init(&sem_cus, 0, INIT);ret = pthread_create(&tid_pro, NULL, pro, NULL);//创建线程if(ret != 0){perror("pthread_create");}ret = pthread_create(&tid_cus, NULL, cus, NULL);if(ret != 0){perror("pthread_create");}pthread_join(tid_pro, NULL);//等待线程结束,并回收线程资源pthread_join(tid_cus, NULL);}int main(int argc, char *argv[]){pro_cus();return 0;}





0 0
原创粉丝点击