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 55 56 57 58
| #include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char msg[50] = "message plein";
char msg2[50] = "nouveau message";
char msg3[50] = "";
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond_prod = PTHREAD_COND_INITIALIZER;
pthread_cond_t cond_conso = PTHREAD_COND_INITIALIZER;
void *routine_producteur(void *arg){
while(1){
pthread_mutex_trylock(&mutex);
pthread_cond_wait(&cond_prod,&mutex);
printf("Le thread producteur a ete reveille");
printf("La boite contient : %s",msg);
memcpy(&msg,&msg2,strlen(msg2)+1);
printf("un message a ete depose! \n");
printf("La boite contient : %s",msg);
pthread_cond_signal(&cond_conso);
pthread_mutex_unlock(&mutex);
}
return NULL;
}
void *routine_consommateur(void *arg){
while(1){
pthread_mutex_trylock(&mutex);
pthread_cond_wait(&cond_conso,&mutex);
printf("Le thread consommateur a ete reveille");
printf("La boite contient : %s",msg);
memcpy(&msg,&msg3,strlen(msg3)+1);
printf("un message a ete retire! \n");
printf("La boite contient : %s",msg);
pthread_cond_signal(&cond_prod);
pthread_mutex_unlock(&mutex);
}
return NULL;
}
int main(void){
pthread_t conso_t[4];
pthread_t prod_t[4];
int i;
for(i=0; i<=3; i++){
pthread_create(&conso_t[i], NULL, routine_consommateur, NULL);
pthread_create(&prod_t[i],NULL,routine_producteur, NULL);
}
for(i=0; i<=3; i++){
pthread_join(conso_t[i], NULL);
pthread_join(prod_t[i],NULL);
}
return 0;
} |
Partager