Add the course threads example, fixed.
[TD_SE.git] / threads / exemple1.c
diff --git a/threads/exemple1.c b/threads/exemple1.c
new file mode 100644 (file)
index 0000000..d8cc0ed
--- /dev/null
@@ -0,0 +1,58 @@
+//exemple1.c
+
+#define _REENTRANT
+#include <pthread.h>
+#include <unistd.h>
+#include <stdlib.h>
+#include <stdio.h>
+
+void afficher(int n, char lettre)
+{
+       int j;
+       for (j = 1; j < n; j++) {
+               printf("%c", lettre);
+               fflush(stdout);
+       }
+}
+
+void *threadA(void *inutilise)
+{
+       afficher(100, 'A');
+       printf("\n Fin du thread A\n");
+       fflush(stdout);
+       pthread_exit(NULL);
+}
+
+void *threadC(void *inutilise)
+{
+       afficher(150, 'C');
+       printf("\n Fin du thread C\n");
+       fflush(stdout);
+       pthread_exit(NULL);
+}
+
+void *threadB(void *inutilise)
+{
+       pthread_t thC;
+       pthread_create(&thC, NULL, threadC, NULL);
+       afficher(100, 'B');
+       printf("\n Le thread B attend la fin du thread C\n");
+       pthread_join(thC, NULL);
+       printf("\n Fin du thread B\n");
+       fflush(stdout);
+       pthread_exit(NULL);
+}
+
+int main()
+{
+       pthread_t thA, thB;
+       printf("Création du Thread A\n");
+       pthread_create(&thA, NULL, threadA, NULL);
+       pthread_create(&thB, NULL, threadB, NULL);
+       sleep(1);               // simule un traitement
+       printf("Le processus principal attend que les autres se terminent\n");
+       // attendre la fin des threads
+       pthread_join(thA, NULL);
+       pthread_join(thB, NULL);
+       exit(0);
+}