相关知识:
操作系统老师布置了一道课后作业题,要求使用P-V操作实现类似“多个生产者、多个消费者共享一个缓冲区”的程序。如下:
题目要求:
父亲放苹果,女儿吃苹果;母亲放桔子,儿子吃桔子。
分析:
父亲、母亲即生产者,女儿、儿子即消费者。
盘子(即缓冲区)会有三种状态,即“空”、“有苹果”、“有桔子”。
代码:
1 #include <stdio.h> 2 #include <string.h> 3 #include <stdlib.h> 4 #include <unistd.h> 5 #include <pthread.h> 6 #include<semaphore.h> 7 8 9 #define P sem_wait 10 #define V sem_post 11 #define fulla &full_real 12 #define fullo &full_real 13 #define empty &empty_real 14 15 16 sem_t full_real; 17 sem_t empty_real; 18 19 int num=0; 20 21 22 //father 23 void* father() 24 { 25 while(num<50) 26 { 27 P(empty); 28 num++; 29 printf("放苹果 %d\n",num); 30 V(fulla); 31 32 } 33 } 34 35 //daughter 36 void* daughter() 37 { 38 while(num<50) 39 { 40 P(fulla); 41 num++; 42 printf("吃苹果 %d\n",num); 43 V(empty); 44 } 45 } 46 47 //mother 48 void* mother() 49 { 50 while(num<50) 51 { 52 P(empty ); 53 num++; 54 printf("放桔子 %d\n",num); 55 V(fullo); 56 57 } 58 } 59 60 //son 61 void* son() 62 { 63 while(num<50) 64 { 65 P(fullo); 66 num++; 67 printf("吃桔子 %d\n",num); 68 V(empty); 69 } 70 } 71 72 int main() 73 { 74 75 sem_init(fulla, 0, 0); 76 sem_init(fullo, 0, 0); 77 sem_init(empty, 0, 1); 78 79 pthread_t tid0; 80 pthread_t tid1; 81 pthread_t tid2; 82 pthread_t tid3; 83 pthread_create(&tid0, NULL, father, NULL); 84 pthread_create(&tid1, NULL, daughter, NULL); 85 pthread_create(&tid2, NULL, mother, NULL); 86 pthread_create(&tid3, NULL, son, NULL); 87 88 pthread_exit(0); 89 }
执行结果: