tpThread2.c
2.08 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
85
86
87
88
89
90
91
92
93
94
95
96
#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);
}