1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
| #include <stdio.h> #include <stdlib.h>
#include <semaphore.h> #include <errno.h> #include <unistd.h> #define total 2 sem_t remain, apple, orange, mutex; static unsigned int vremain = 2, vapple = 0, vorange = 0; void *father(void *); void *mather(void *); void *son1(void *); void *son2(void *); void *daughter1(void *); void *daughter2(void *); void print_sem(); int main() { pthread_t fa, ma, so ,da; sem_init(&remain, 0, total); sem_init(&apple, 0, 0); sem_init(&orange, 0, 0); sem_init(&mutex, 0, 1); pthread_create(&fa, NULL, &father, NULL); pthread_create(&ma, NULL, &mather, NULL); pthread_create(&so, NULL, &son1, NULL); pthread_create(&da, NULL, &daughter1, NULL); pthread_create(&so, NULL, &son2, NULL); pthread_create(&da, NULL, &daughter2, NULL); for(;;); } void *father(void *arg) { while(1) { sem_wait(&remain); sem_wait(&mutex); vremain--; vapple++; printf("父亲放苹果, 剩余空间=%u, 苹果数=%u\n", vremain, vapple); sem_post(&mutex); sem_post(&apple); sleep(1); } } void *mather(void *arg) { while(1) { sem_wait(&remain); sem_wait(&mutex); vremain--; vorange++; printf("母亲放橘子, 剩余空间=%u, 橘子数=%u\n", vremain, vorange); sem_post(&mutex); sem_post(&orange); sleep(2); } } void *son1(void *arg) { while(1) { sem_wait(&orange); sem_wait(&mutex); vremain++; vorange--; printf("儿子吃橘子, 剩余空间=%u, 橘子数=%u\n", vremain, vorange); sem_post(&mutex); sem_post(&remain); sleep(3); } } void *son2(void *arg) { while(1) { sem_wait(&orange); sem_wait(&mutex); vremain++; vorange--; printf("儿子2吃橘子, 剩余空间=%u, 橘子数=%u\n", vremain, vorange); sem_post(&mutex); sem_post(&remain); sleep(3); } } void *daughter1(void *arg) { while(1) { sem_wait(&apple); sem_wait(&mutex); vremain++; vapple--; printf("女儿1吃苹果, 剩余空间=%u, 苹果数=%u\n", vremain, vapple); sem_post(&mutex); sem_post(&remain); sleep(3); } } void *daughter2(void *arg) { while(1) { sem_wait(&apple); sem_wait(&mutex); vremain++; vapple--; printf("女儿2吃苹果, 剩余空间=%u, 苹果数=%u\n", vremain, vapple); sem_post(&mutex); sem_post(&remain); sleep(3); } } void print_sem() { int val1, val2, val3; sem_getvalue(&remain, &val1); sem_getvalue(&apple, &val2); sem_getvalue(&orange, &val3); printf("Semaphore: remain:%d, apple:%d, orange:%d\n", val1, val2, val3); }
|