28eadbabae4f08ce631f99bd8250c09bf2c97933
[TD_SE.git] / semaphore / semaphore.c
1 #include <semaphore.h> // pour les sémaphores
2 #include <pthread.h> // pour pthread_create et pthread_join
3 #include <stdio.h> // pour printf
4
5 #define val 1
6 sem_t mutex; // sémaphore
7 int var_glob = 0;
8
9 void *increment(void *);
10 void *decrement(void *);
11
12 int main()
13 {
14 pthread_t threadA, threadB;
15 sem_init(&mutex, 0, val); // initialiser mutex
16 printf("ici main : var_glob = %d\n", var_glob);
17 // création d'un thread pour increment
18 pthread_create(&threadA, NULL, increment, NULL);
19 // création d'un thread pour decrement
20 pthread_create(&threadB, NULL, decrement, NULL);
21 // attendre la fin des threads
22 pthread_join(threadA, NULL);
23 pthread_join(threadB, NULL);
24 printf("ici main, fin threads : var_glob =%d \n", var_glob);
25 return 0;
26 }
27
28 void *decrement(void *nothing)
29 {
30 sem_wait(&mutex); // attendre l'autorisation d'accès
31 var_glob = var_glob - 1;
32 printf("ici sc de decrement: var_glob= %d\n", var_glob);
33 sem_post(&mutex);
34 return (NULL);
35 }
36
37 void *increment(void *nothing)
38 {
39 sem_wait(&mutex);
40 var_glob = var_glob + 1;
41 printf("ici sc de increment: var_glob= %d\n", var_glob);
42 sem_post(&mutex);
43 return (NULL);
44 }