Commit | Line | Data |
---|---|---|
e5997403 JB |
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 | |
151a0f56 | 7 | static int var_glob = 0; |
e5997403 JB |
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); | |
151a0f56 | 24 | printf("ici main, fin threads : var_glob = %d\n", var_glob); |
e5997403 JB |
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); | |
151a0f56 | 34 | return NULL; |
e5997403 JB |
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); | |
151a0f56 | 43 | return NULL; |
e5997403 | 44 | } |