Wiki ~ namok.be

rtlinux > rtlinux_pthread_simple

Un exemple simple d'utilisation d'un mutex .. en fait l'exemple bateau du “solde du compte en banque”

#include <pthread.h>
#include<stdlib.h>
#include<sched.h>
#include"couleurs.h"
 
/* 
 * mutex
 * 
 * Example of use of mutex
 * I have 100 EUR on my bank account.  
 *    
 * To see utility of mutex decomment line 53 and 60
 */   
 
#define N_THREAD 5
#define N_ALEATOIRE  1+(int) (10.0*rand()/(RAND_MAX+1.0))
 
const char* COULEUR[] = {RED, BLUE, YELLOW, GREEN, LIGHT_BLUE} ; 
 
pthread_t tids[N_THREAD] ;          // array of thread
pthread_mutex_t mid ;               // mutex
int balance ;                          // balance of bank account
 
 
void* get_cash(void*) ;
 
int main() {
   int i ;           // loop indice
 
   // initialisation rand
   srand(5) ; 
 
   balance = 100 ; 
   printf("Balance : %d \n", balance) ; 
 
   pthread_mutex_init( &mid, NULL) ; 
   for ( i=0; i<N_THREAD; i++) {
      pthread_create( &tids[i], NULL, get_cash, (void*)i) ; 
   } // end - for  
 
   for (i=0; i<N_THREAD; i++)    pthread_join(tids[i], NULL) ; 
   exit(0) ; 
} // end - main  
 
 
void* get_cash(void* j) {
   int amount ;                     // amout of money
   int id = (int) j ;
   int balance_tmp ;             // use to "facilitate" scheduling 
 
   while (balance > 0) {
      amount = N_ALEATOIRE ;
      //pthread_mutex_lock(&mid) ; 
      balance_tmp = balance ;
      printf("%sThread %d, get %d EUR. %s\n",COULEUR[id], id, amount, DEFAULT) ;
      balance_tmp -= amount ;
      sched_yield() ;         // yield execution to another thread
      balance = balance_tmp ;
      printf("%sThread %d, balance : %d \n%s",COULEUR[id], id, balance, DEFAULT);
      //pthread_mutex_unlock(&mid) ; 
      sched_yield() ;         // yield execution to another thread
   } // end -     for  
 
 
} // end - get_cash
Remarque

J'utilise un header pour écrire les phrase en couleur → couleur.h