Add posix semaphore course example code.
[TD_SE.git] / semaphore / semaphore.c
diff --git a/semaphore/semaphore.c b/semaphore/semaphore.c
new file mode 100644 (file)
index 0000000..28eadba
--- /dev/null
@@ -0,0 +1,44 @@
+#include <semaphore.h>         // pour les sémaphores
+#include <pthread.h>           // pour pthread_create et pthread_join
+#include <stdio.h>             // pour printf
+
+#define val 1
+sem_t mutex;                   // sémaphore
+int var_glob = 0;
+
+void *increment(void *);
+void *decrement(void *);
+
+int main()
+{
+       pthread_t threadA, threadB;
+       sem_init(&mutex, 0, val);       // initialiser mutex
+       printf("ici main : var_glob = %d\n", var_glob);
+       // création d'un thread pour increment
+       pthread_create(&threadA, NULL, increment, NULL);
+       // création d'un thread pour decrement
+       pthread_create(&threadB, NULL, decrement, NULL);
+       // attendre la fin des threads
+       pthread_join(threadA, NULL);
+       pthread_join(threadB, NULL);
+       printf("ici main, fin threads : var_glob =%d \n", var_glob);
+       return 0;
+}
+
+void *decrement(void *nothing)
+{
+       sem_wait(&mutex);       // attendre l'autorisation d'accès
+       var_glob = var_glob - 1;
+       printf("ici sc de decrement: var_glob= %d\n", var_glob);
+       sem_post(&mutex);
+       return (NULL);
+}
+
+void *increment(void *nothing)
+{
+       sem_wait(&mutex);
+       var_glob = var_glob + 1;
+       printf("ici sc de increment: var_glob= %d\n", var_glob);
+       sem_post(&mutex);
+       return (NULL);
+}