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 59 60 61 62 63 64 65 66
| #include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char msg[50] = "message";
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){
int i = (int *)arg;
while(1){
pthread_mutex_lock(&mutex);
while (msg[0] != ' '){
pthread_cond_wait(&cond_prod,&mutex);
}
printf("\n\n\n\n\n Le thread producteur a ete reveille");
printf("La boite contient : %s",msg);
memcpy(&msg,&msg2,strlen(msg2)+1);
printf("un message a ete depose! par le producteur %d\n",i);
printf("La boite contient : %s",msg);
pthread_cond_signal(&cond_conso);
pthread_mutex_unlock(&mutex);
}
return NULL;
}
void *routine_consommateur(void *arg){
int i = (int *)arg;
while(1){
pthread_mutex_lock(&mutex);
while(msg[0] == ' '){
pthread_cond_wait(&cond_conso,&mutex);
}
printf("\n\n\n\n\nLe thread consommateur a ete reveille \n");
printf("La boite contient : %s \n",msg);
memcpy(&msg,&msg3,strlen(msg3)+1);
printf("un message a ete retire par le consommateur %d! \n",i);
printf("La boite contient : %s \n",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, (void*)i);
pthread_create(&prod_t[i],NULL,routine_producteur, (void*)i);
}
for(i=0; i<=3; i++){
pthread_join(conso_t[i], NULL);
pthread_join(prod_t[i],NULL);
}
printf(" Message => %s \n",msg);
return 0;
} |
Partager