Add the prod cons code snippet.
[TD_SE.git] / prodcons / prodcons.c
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 void *prod(void *arg);
15 void *cons(void *arg);
16
17 int main()
18 {
19 pthread_t t1, t2;
20 args_t args;
21 sem_init(&args.sem_free, 0, BUF_SIZE);
22 sem_init(&args.sem_busy, 0, 0);
23 pthread_create(&t1, NULL, prod, &args);
24 pthread_create(&t2, NULL, cons, &args);
25 pthread_join(t1, NULL);
26 pthread_join(t2, NULL);
27 printf("exit\n");
28 return EXIT_SUCCESS;
29 }
30
31 void *prod(void *arg)
32 {
33 int ip = 0, nbprod = 0, obj = 1001;
34 args_t *args = (args_t *) arg;
35 while (nbprod < MAX) {
36 sem_wait(&args->sem_free);
37 buf[ip] = obj;
38 sem_post(&args->sem_busy);
39 printf("prod: buf[%d]=%d\n", ip, obj);
40 obj++;
41 nbprod++;
42 ip = (ip + 1) % BUF_SIZE;
43 }
44 return NULL;
45 }
46
47 void *cons(void *arg)
48 {
49 int ic = 0, nbcons = 0, obj;
50 args_t *args = (args_t *) arg;
51 while (nbcons < MAX) {
52 sleep(1);
53 sem_wait(&args->sem_busy);
54 obj = buf[ic];
55 sem_post(&args->sem_free);
56 printf("cons: buf[%d]=%d\n", ic, obj);
57 nbcons++;
58 ic = (ic + 1) % BUF_SIZE;
59 }
60 return NULL;
61 }