tpThread2.c 2.08 KB
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#define MAX 		10

int tab[MAX];
int nb=0;
pthread_mutex_t mutex;
struct minMax {
    int *min;
    int *max;
    };

void lire() {
	int i;
	printf("saisir %d entiers\n", MAX);
	for (i=0; i<MAX ; i++) scanf("%d", &tab[i]);
}
void affiche(){
	int i;
	printf("entiers saisis :");
	for (i=0; i<MAX ; i++) printf("%d ",tab [i]);
	printf("\n");
}
void * moyenne(void* arg){
	int i, moy=tab[0];
	for (i=1; i<MAX; i++) moy = moy + tab[i];
	printf("moyenne des entiers = %f\n", (float)moy/MAX);
}
void * supSeuil(void* arg){
	int i;
    int seuil =*(int*)arg;
    for (i=0; i<MAX; i++){
        if (tab[i]>seuil){
            pthread_mutex_lock(&mutex);
            nb++;
            pthread_mutex_unlock(&mutex);   
        }
    }
     
}
void * infSeuil(void* arg){
    int i;
    int seuil =*(int*)arg;
    
    for (i=0; i<MAX; i++){
        if (tab[i]<seuil){
            pthread_mutex_lock(&mutex);
            nb++;
            pthread_mutex_unlock(&mutex);   
        }
    }
}

void * minMax(void * arg) {
	int i;
    struct minMax str_minMax = *(struct minMax *)arg;
	*str_minMax.min=tab[0];
	*str_minMax.max=tab[0];
	for (i=1; i<MAX; i++) {
	    if (tab[i]<*str_minMax.min) *str_minMax.min=tab[i];
	    else if (tab[i]>*str_minMax.max) *str_minMax.max=tab[i];
	}
}

int main(){
	int seuilInf, seuilSup, min, max;
    pthread_t tid1, tid2, tid3, tid4;
 
    pthread_mutex_init(&mutex,NULL);
   
	lire();
	affiche();
    
    pthread_create(&tid1, NULL, moyenne, NULL); 
    
	printf("saisir les seuils sup et inf : ");
	scanf("%d%d", &seuilSup, &seuilInf);
 
    pthread_join(tid1,NULL);
    pthread_create(&tid2, NULL, supSeuil,(void *) &seuilSup);
    pthread_create(&tid3, NULL, infSeuil,(void *) &seuilInf);
    pthread_join(tid2,NULL);
    pthread_join(tid3,NULL);
    
    struct minMax str_minMax;

    str_minMax.min = &min;
    str_minMax.max = &max;
    pthread_create(&tid4, NULL, minMax,(void *) &str_minMax);
	    
    pthread_join(tid4,NULL);
	printf("min = %d, max = %d\nnb=%d", *str_minMax.min, *str_minMax.max, nb);
    pthread_exit(NULL);
	return(0);
}