Participer au site avec un Tip
Rechercher
 

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 :

Fonction thrd_join (C ISO 2011)

La fonction thrd_exit La fonction thrd_sleep


La vidéo


Attendre la terminaison d'un thread via la fonction thrd_join

Entête à  inclure

#include <threads.h>

Fonction thrd_join

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.

Paramètres

Valeur de retour

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.

Exemple de code

 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;
}
Fichier sample.c : exemple de démarrage et d'attente de la fin de traitement de dix threads.

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
$>

Fonctions et types connexes

thrd_busy, thrd_error, thrd_nomem, thrd_success, thrd_timedout
thrd_create
thrd_detach
thrd_exit


La fonction thrd_exit La fonction thrd_sleep