Commit | Line | Data |
---|---|---|
6b2a29ce | 1 | #include <unistd.h> |
23ab6af8 JB |
2 | #include <pthread.h> |
3 | #include <stdlib.h> | |
6b2a29ce JB |
4 | #include <stdio.h> |
5 | #include <semaphore.h> | |
6 | ||
7 | static int db = 42; | |
8 | static int NbL = 0; | |
9 | sem_t mutex; | |
10 | sem_t redact; | |
11 | ||
12 | static void *lecteur(void *arg) | |
13 | { | |
14 | while (1) { | |
15 | sem_wait(&mutex); | |
16 | if (NbL == 0) | |
17 | sem_wait(&redact); | |
18 | NbL++; | |
19 | sem_post(&mutex); | |
20 | // lecture de la base | |
21 | sleep(1); | |
22 | printf("lecteur bd=%d\n", db); | |
23 | // fin de l’accès à la base | |
24 | sem_wait(&mutex); | |
25 | NbL--; | |
26 | if (NbL == 0) | |
27 | sem_post(&redact); | |
28 | sem_post(&mutex); | |
29 | } | |
6773299b | 30 | return NULL; |
6b2a29ce JB |
31 | } |
32 | ||
33 | static void *redacteur(void *arg) | |
34 | { | |
35 | while (1) { | |
36 | sem_wait(&redact); | |
37 | // modifier les données de la base | |
38 | db++; | |
39 | printf("redacteur bd=%d\n", db); | |
ddfab1b0 | 40 | sleep(1); |
6b2a29ce JB |
41 | sem_post(&redact); |
42 | } | |
6773299b | 43 | return NULL; |
6b2a29ce JB |
44 | } |
45 | ||
46 | int main() | |
47 | { | |
23ab6af8 | 48 | pthread_t t1, t2; |
ddfab1b0 JB |
49 | sem_init(&mutex, 0, 1); |
50 | sem_init(&redact, 0, 1); | |
23ab6af8 JB |
51 | pthread_create(&t1, NULL, redacteur, NULL); |
52 | pthread_create(&t2, NULL, lecteur, NULL); | |
53 | pthread_join(t1, NULL); | |
54 | pthread_join(t2, NULL); | |
55 | printf("exit\n"); | |
56 | return EXIT_SUCCESS; | |
6b2a29ce | 57 | } |