#include <threads.h>
typedef unsigned long int thrd_t;
Le type thrd_t
représente un identifiant de thread. La majorité des fonctions de manipulation de threads utilisent ce type de données.
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 |
#include <stdio.h> #include <stdlib.h> #include <threads.h> // La fonction sur laquelle va démarrer notre thread int threadMain( void * data ) { for( int i=0; i<1000000; i++ ) { printf( "Ca tourne\n" ); } return thrd_success; } int main() { // On crée un thread. thrd_t myThread; if ( thrd_create( &myThread, threadMain, NULL ) != thrd_success ) { fprintf( stderr, "Cannot create 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 :