Properly init the semaphore in the readers/writers code.
[TD_SE.git] / lecteursredacteurs / lecteursredacteurs.c
1 #include <unistd.h>
2 #include <pthread.h>
3 #include <stdlib.h>
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 }
30 return NULL;
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);
40 sleep(1);
41 sem_post(&redact);
42 }
43 return NULL;
44 }
45
46 int main()
47 {
48 pthread_t t1, t2;
49 sem_init(&mutex, 0, 1);
50 sem_init(&redact, 0, 1);
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;
57 }