Add for real the philosophe code snippet.
[TD_SE.git] / prodcons / prodcons.c
CommitLineData
66c9107f
JB
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
9typedef struct args {
10 sem_t sem_free;
11 sem_t sem_busy;
12} args_t;
13static int buf[BUF_SIZE];
14void *prod(void *arg);
15void *cons(void *arg);
16
17int 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
31void *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
47void *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}