#include #include #include #include #include #include #include #include /* declaration des constantes */ #define TAILLE 100 /* declaration des semaphores */ pthread_mutex_t mutex ; /* declaration d'un mutex */ pthread_cond_t plein ; /* condition */ pthread_cond_t vide ; /* condition */ int tailleCourante,i; /* condition pour lire */ char tampon[BUFSIZ] ; void * producteur (void*); void * consomateur (void*); /* ceclaration des variables patagées */ void * producteur (void * bidon) { pthread_mutex_lock(&mutex) ; while (tailleCourante == 1) pthread_cond_wait(&vide,&mutex); tampon [tailleCourante] = 'A' ; tailleCourante++ ; printf("producteur %s\n",tampon); pthread_cond_signal(&plein) ; pthread_mutex_unlock(&mutex) ; return NULL ; } void * consommateur (void *bidon) { pthread_mutex_lock(&mutex) ; while (tailleCourante == 0) pthread_cond_wait(&plein,&mutex); tailleCourante-- ; printf("consommateur %s\n",tampon); pthread_cond_signal(&vide) ; pthread_mutex_unlock(&mutex) ; return NULL ; } int main(void) { /* declaration des thread */ pthread_t tproducteur[20]; pthread_t tconsomateur[20] ; for(i = 0; i < 20 ; i++) { /* creation du tread producteur*/ pthread_create(&tproducteur[i],NULL,producteur,NULL); /* creation du tread consomateur */ pthread_create(&tconsomateur[i],NULL,consommateur,NULL); } /* On va bloquer le tread initail pour attendre la fin des thread */ for(i = 0; i < 20 ; i++) { pthread_join(tproducteur[i],NULL); pthread_join(tconsomateur[i],NULL); } exit (0); }