| 1 | #include <semaphore.h> |
| 2 | #include <unistd.h> |
| 3 | #include <pthread.h> |
| 4 | #include <stdio.h> |
| 5 | #include <stdlib.h> |
| 6 | |
| 7 | #define MAX 6 |
| 8 | #define BUF_SIZE 3 |
| 9 | typedef struct args { |
| 10 | sem_t sem_free; |
| 11 | sem_t sem_busy; |
| 12 | } args_t; |
| 13 | static int buf[BUF_SIZE]; |
| 14 | |
| 15 | void *prod(void *arg); |
| 16 | void *cons(void *arg); |
| 17 | |
| 18 | int main() |
| 19 | { |
| 20 | pthread_t t1, t2; |
| 21 | args_t args; |
| 22 | sem_init(&args.sem_free, 0, BUF_SIZE); |
| 23 | sem_init(&args.sem_busy, 0, 0); |
| 24 | pthread_create(&t1, NULL, prod, &args); |
| 25 | pthread_create(&t2, NULL, cons, &args); |
| 26 | pthread_join(t1, NULL); |
| 27 | pthread_join(t2, NULL); |
| 28 | printf("exit\n"); |
| 29 | return EXIT_SUCCESS; |
| 30 | } |
| 31 | |
| 32 | void *prod(void *arg) |
| 33 | { |
| 34 | int ip = 0, nbprod = 0, obj = 1001; |
| 35 | args_t *args = (args_t *) arg; |
| 36 | while (nbprod < MAX) { |
| 37 | sem_wait(&args->sem_free); |
| 38 | buf[ip] = obj; |
| 39 | sem_post(&args->sem_busy); |
| 40 | printf("prod: buf[%d]=%d\n", ip, obj); |
| 41 | obj++; |
| 42 | nbprod++; |
| 43 | ip = (ip + 1) % BUF_SIZE; |
| 44 | } |
| 45 | return NULL; |
| 46 | } |
| 47 | |
| 48 | void *cons(void *arg) |
| 49 | { |
| 50 | int ic = 0, nbcons = 0, obj; |
| 51 | args_t *args = (args_t *) arg; |
| 52 | while (nbcons < MAX) { |
| 53 | sleep(1); |
| 54 | sem_wait(&args->sem_busy); |
| 55 | obj = buf[ic]; |
| 56 | sem_post(&args->sem_free); |
| 57 | printf("cons: buf[%d]=%d\n", ic, obj); |
| 58 | nbcons++; |
| 59 | ic = (ic + 1) % BUF_SIZE; |
| 60 | } |
| 61 | return NULL; |
| 62 | } |