Wiki ~ namok.be

rtlinux > rtlinux_pthread_simple

Un exemple simple de lancement de deux threads …

#include <pthread.h>
#include<unistd.h>
 
/*
 * un.c
 *
 * First example for using thread. I create 2 threads who count to 10. 
 */
 
/*
 * run
 *
 * method executed when thread create
 */
void* run (void* arg) {
   int i; 
   int id = (int) arg ; 
 
   printf("Mon id est %d\n",id) ;
 
   for (i=0; i<10 ; i++) {
      printf( "Thread %d, I count %d\n", pthread_self(), i) ;
      sleep(1+id); 
   }
   pthread_exit(0);
} // end - run  
 
 
int main ( int argc, char* argv[] )  {
   // Create 2 threads
   pthread_t task1, task2 ; 
 
   pthread_create (&task1, NULL, run, (void*)0 ) ; 
   pthread_create (&task2, NULL, run, (void*)1 ) ; 
   pthread_join(task1, NULL) ; 
   pthread_join(task2, NULL) ; 
 
   exit(0); 
} // end - main