#include <threads.h>
int thrd_join( thrd_t thread, int * threadResultCode );
Cette fonction permet d'attendre la fin d'exécution d'un thread et de récupérer son code de sortie.
int) qui recevra le code de sortie du thread.
Conventionnellement parlant, la fonction startFunction doit renvoyer 0 si tout se passe bien et une autre valeur dans le cas contraire.
La fonction thrd_join renvoie la valeur thrd_success si l'attente du thread se passe correctement.
Dans le cas contraire, elle renverra thrd_error.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
#include <stdio.h> #include <stdlib.h> #include <threads.h> #define LOOP_COUNT 1000000 #define THREAD_COUNT 10 // La fonction sur laquelle vont démarrer nos dix threads. int threadMain( void * data ) { long threadIndex = (long) data; for ( int i=0; i<LOOP_COUNT; i++ ) { printf( "Thread %ld affiche %d\n", threadIndex, i ); } printf( "Thread %ld terminé\n", threadIndex ); return thrd_success; } int main() { // On réserve la mémoire pour dix descripteurs de threads. thrd_t threads[10]; // On crée nos 10 threads. for( int i=0; i<THREAD_COUNT; i++ ) { if ( thrd_create( &threads[i], threadMain, (void *)(long)i ) != thrd_success ) { fprintf( stderr, "Impossible de créer le thread %d\n", i ); return EXIT_FAILURE; } } // On attends que les dix threads aient terminés leur traitement. for( int i=0; i<THREAD_COUNT; i++ ) { int threadResultCode; if ( thrd_join( threads[i], &threadResultCode ) == thrd_error ) { fprintf( stderr, "Impossible d'attendre le thread %d\n", i ); return EXIT_FAILURE; } if ( threadResultCode != 0 ) { fprintf( stderr, "Le thread %d a terminé anormalement\n", i ); } } // On sort du programme. printf( "Le thread initial/principal s'arrête.\n" ); return EXIT_SUCCESS; } |
Pour compiler cet exemple sous environnement Linux/Unix, il est nécessaire de lier la librairie pthread (Posix Thread) à votre exécutable. Voici un exemple de compilation.
$> gcc -o sample sample.c -lpthread $>
Améliorations / Corrections
Vous avez des améliorations (ou des corrections) à proposer pour ce document : je vous remerçie par avance de m'en faire part, cela m'aide à améliorer le site.
Emplacement :
Description des améliorations :