École Supérieure des Sciences et de la Technologie de Hammam Sousse
TP : Système D’exploitation 2 Durée : 1h30 / Classe : LI1
Enseignant : Ben Khlifa Hamza Année universitaire : 2025-2026
💻 Correction TP3 : Gestion des Threads
Exercice 1 : Création d'un Thread (Facile)
Correction
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
// Fonction ex cut e par le thread
void *fonction_thread(void *arg) {
printf("[Thread] ID: %lu - Bonjour depuis le thread secondaire !\n", pthread_self());
pthread_exit(NULL);
}
int main() {
pthread_t thread;
// Cr ation du thread
if (pthread_create(&thread, NULL, fonction_thread, NULL) != 0) {
perror("Erreur lors de la cr ation du thread");
exit(EXIT_FAILURE);
}
printf("[Main] ID: %lu - Bonjour depuis le thread principal !\n", pthread_self());
// Attendre la fin du thread secondaire
pthread_join(thread, NULL);
return 0;
}
Explication
• Un thread est créé et exécute fonction_thread().
• pthread_create() lance le thread.
• pthread_join() attend que le thread se termine avant de quitter.
1/3
TP : Système D’exploitation 2 Durée : 1h30 / Classe : LI1
Enseignant : Ben Khlifa Hamza Année universitaire : 2025-2026
💻 Correction TP3 : Gestion des Threads
Exercice 1 : Création d'un Thread (Facile)
Correction
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
// Fonction ex cut e par le thread
void *fonction_thread(void *arg) {
printf("[Thread] ID: %lu - Bonjour depuis le thread secondaire !\n", pthread_self());
pthread_exit(NULL);
}
int main() {
pthread_t thread;
// Cr ation du thread
if (pthread_create(&thread, NULL, fonction_thread, NULL) != 0) {
perror("Erreur lors de la cr ation du thread");
exit(EXIT_FAILURE);
}
printf("[Main] ID: %lu - Bonjour depuis le thread principal !\n", pthread_self());
// Attendre la fin du thread secondaire
pthread_join(thread, NULL);
return 0;
}
Explication
• Un thread est créé et exécute fonction_thread().
• pthread_create() lance le thread.
• pthread_join() attend que le thread se termine avant de quitter.
1/3