#include <threads.h>
typedef int (*thrd_start_t) (void*);
Pour démarrer un nouveau thread, vous devez commencer à coder une fonction qui correspondra au point d'entrée de ce nouveau thread.
Cette fonction devra être compatible à la signature définie par le type thrd_start_t
(un type pointeur sur fonction).
Dans cet exemple, on utilise le type thrd_start_t
pour conditionner la fonction à exécuter (lignes 27 et suivantes).
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 49 50 51 52 53 54 |
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <threads.h> // Deux fonctions pouvant être démarrées par un thread. int simpleAlgo( void * data ) { printf( "Imagez un algorithm simple à exécuter pas ce thread.\n" ); return thrd_success; } int complexAlgo( void * data ) { printf( "Imagez un algorithm complexe à exécuter pas ce thread.\n" ); return thrd_success; } int main( int argc, char * argv[] ) { // On test le nombre d'arguments sur la ligne de commande if ( argc != 2 ) { printf( "Usage: sample mode\n" ); printf( "\tOu mode peut valoir 'simple' ou 'complex'.\n" ); exit( EXIT_SUCCESS ); } // On choisi le bon algorithme thrd_start_t algo; if ( strcmp( argv[1], "simple" ) == 0 ) { algo = simpleAlgo; } else { algo = complexAlgo; } // On crée le thread. thrd_t myThread; if ( thrd_create( &myThread, algo, NULL ) != thrd_success ) { fprintf( stderr, "Impossible de créer le thread\n" ); return EXIT_FAILURE; } // On attent la fin d'exécution du thread int threadResultCode; if ( thrd_join( myThread, &threadResultCode ) == thrd_error ) { fprintf( stderr, "Impossible d'attendre le thread\n" ); return EXIT_FAILURE; } // 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 :