首页 > 代码库 > C语言调用库函数实现生产者消费者问题
C语言调用库函数实现生产者消费者问题
1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<semaphore.h> 4 #include<pthread.h> 5 #include<unistd.h> 6 7 #define NumOf_Producer 5 //the max num of producer 8 #define NumOf_Consumer 10 //the max num of consumer 9 #define Maxnum 10 // the max num of product 10 sem_t Empty_sem; //the goal of whether the num of product is null 11 sem_t Full_sem; //the goal of whether the num of product is equal to Maxnum 12 13 pthread_mutex_t Mutex; //the goal of whether someone use the buff 14 15 int Producer_id = 0; 16 int Consumer_id = 0; 17 int NowNumOfProduce = 0; 18 void *Producer(void *arg) //the thread of producer 19 { 20 int id = Producer_id++; 21 while(1) 22 { 23 sleep(0.1); 24 sem_wait(&Full_sem); //when it comes to zero ,it means that the num of product is equal to Maxnum 25 pthread_mutex_lock(&Mutex); //lock the buff 26 NowNumOfProduce++; 27 printf("Producerthread %d product one,the num is:%d \n",id%NumOf_Producer,NowNumOfProduce); 28 pthread_mutex_unlock(&Mutex); 29 sem_post(&Empty_sem); //when it comes to ten ,it means there are ten products can be used by consumer 30 } 31 32 return ((void *)0); 33 } 34 35 void *Consumer(void *arg) 36 { 37 int id = Consumer_id++; 38 while(1) 39 { 40 sleep(0.2); 41 sem_wait(&Empty_sem); 42 pthread_mutex_lock(&Mutex); 43 NowNumOfProduce--; 44 printf("Consumerthread %d use product one,the num is:%d \n",id%NumOf_Consumer,NowNumOfProduce); 45 pthread_mutex_unlock(&Mutex); 46 sem_post(&Full_sem); 47 } 48 return ((void *)0); 49 } 50 51 int main() 52 { 53 pthread_t Con[NumOf_Consumer]; 54 pthread_t Pro[NumOf_Producer]; 55 56 int temp1 = sem_init(&Empty_sem,0,0); 57 int temp2 = sem_init(&Full_sem,0,Maxnum); 58 if(temp1&&temp2!=0) 59 { 60 printf("sem init failed \n"); 61 exit(1); 62 } 63 64 int temp3 = pthread_mutex_init(&Mutex,NULL); 65 66 if(temp3!=0) 67 { 68 printf("Mutex init failed \n"); 69 exit(1); 70 } 71 72 for(int i=0 ;i<NumOf_Producer;i++) 73 { 74 int temp4 = pthread_create(&Pro[i],NULL,Producer,(void *)&i); 75 if(temp4!=0) 76 { 77 printf("thread create failed !\n"); 78 exit(1); 79 } 80 } 81 82 for(int i=0;i<NumOf_Consumer;i++) 83 { 84 int temp5 = pthread_create(&Con[i],NULL,Consumer,(void *)&i); 85 if(temp5!=0) 86 { 87 printf("thread create failed !\n"); 88 } 89 exit(1); 90 } 91 //destroy the thread 92 for(int i=0;i<NumOf_Consumer;i++) 93 { 94 pthread_join(Con[i],NULL); 95 } 96 97 for(int i=0;i<NumOf_Producer;i++) 98 { 99 pthread_join(Pro[i],NULL);100 }101 102 return 0;103 }
说明:unisted.h是用来调用sleep,pthread.h是linux系统下线程编程的库,semaphore.h是使用信号灯的函数库,至于那些初始化方法,wait方法,post等可以去查查的。如果在编译程序时候出现类似sem_t未定义等问题,需要设置一下link链接,找到linux系统下安装的lib库中的libpthread.so导入进去就好了。
C语言调用库函数实现生产者消费者问题
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。