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 67 68 69 70 71 72 73 74 75
| #include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
pthread_cond_t autoContinuer = PTHREAD_COND_INITIALIZER;
pthread_cond_t autoStart = PTHREAD_COND_INITIALIZER;
#define NB_RDV 3
#define NB_THREADS 9
int iRdv=0;
pthread_mutex_t emAffichage = PTHREAD_MUTEX_INITIALIZER;//init à 1
int continuer=0;
int nbFini=0;
void traitement_principal(){
if(iRdv==NB_RDV){
iRdv=0;
continuer+=1;
printf("Thread %lu, je débloques ceux en attente \n",pthread_self());
pthread_cond_broadcast(&autoContinuer);
}else{
continuer+=1;
}
while(continuer < NB_RDV){
printf("Thread %lu, j'attends' \n",pthread_self());
pthread_cond_wait(&autoContinuer,&emAffichage);
}
printf("Thread %lu, je finis mon traitement\n",pthread_self());
nbFini++;
if(nbFini==NB_RDV){
continuer=0;
}
while(continuer==0){
pthread_cond_broadcast(&autoStart);
}
}
void* traitement(){
pthread_mutex_lock (&emAffichage);//demande accès
while(continuer!=0 && iRdv==0){
pthread_cond_wait(&autoStart,&emAffichage);
}
printf("Thread %lu, je commence mon traitement \n",pthread_self());
iRdv+=1;
traitement_principal();
pthread_mutex_unlock (&emAffichage);//rend accès
pthread_exit((void *)NULL);
}
void thdErreur(int codeErr, char *msgErr, void *codeArret) {
fprintf(stderr, "%s: %d soit %s \n", msgErr, codeErr, strerror(codeErr));
pthread_exit(codeArret);
}
int main(int argc, char const *argv[])
{
int etat;
pthread_t idThd[NB_THREADS];
for(int i = 0; i < NB_THREADS; i++){
if ((etat = pthread_create(&idThd[i], NULL, traitement,NULL)) != 0)
thdErreur(etat, "Creation thread avec rdv",NULL);
}
/* Attendre la fin des threads afficheur car si le thread principal
- i.e. le main() - se termine, les threads fils crees meurent aussi */
for (int i = 0; i < NB_THREADS; i++)
if ((etat = pthread_join(idThd[i], NULL)) != 0)
thdErreur(etat, "Join threads afficheurs", NULL);
printf ("\nFin de l'execution du thread principal \n");
return 0;
} |
Partager