tpThread.c
1.91 KB
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
76
77
78
79
80
81
82
83
84
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#define MAX 10
int tab[MAX];
int nb=0;
pthread_mutex_t mutex;
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;
pthread_mutex_lock(&mutex);
for (i=0; i<MAX; i++) if (tab[i]>seuil) nb++;
printf("fin de fonction supSeuil : nb = %d\n", nb);
pthread_mutex_unlock(&mutex);
}
void * infSeuil(void* arg){
int i;
int seuil =*(int*)arg;
pthread_mutex_lock(&mutex);
for (i=0; i<MAX; i++) if (tab[i]<seuil) nb++;
printf("fin de fonction infSeuil : nb = %d\n", nb);
pthread_mutex_unlock(&mutex);
}
void minMax(int *min, int *max) {
int i;
*min=tab[0];
*max=tab[0];
for (i=1; i<MAX; i++) {
if (tab[i]<*min) *min=tab[i];
else if (tab[i]>*max) *max=tab[i];
}
}
int main(){
int seuilInf, seuilSup, min, max;
pthread_t tid1, tid2, tid3;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
pthread_mutex_init(&mutex,NULL);
lire();
affiche();
pthread_create(&tid1, &attr, moyenne, NULL);
printf("saisir les seuils sup et inf : ");
scanf("%d%d", &seuilSup, &seuilInf);
int * p_seuilInf = (int *) malloc(sizeof(int));
*p_seuilInf = seuilInf;
int * p_seuilSupp = (int *) malloc(sizeof(int));
*p_seuilSupp = seuilSup;
pthread_create(&tid2, &attr, supSeuil,(void *) p_seuilSupp);
pthread_create(&tid3, &attr, infSeuil,(void *) p_seuilInf);
minMax(&min, &max);
printf("min = %d, max = %d\n", min, max);
pthread_exit(NULL);
return(0);
}