cours_prog_systeme/TD/TD6/main.c
2021-08-22 13:28:10 +02:00

77 lines
No EOL
1.8 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/time.h>
#define NB_THREAD 4
#define F 10000000
// Nombre de point à l'intérieur du cercle
int retvals[NB_THREAD];
int t_num = 0;
/// Fonction de calcul en thread
void * fn_thread (void * p_int) {
// Le thread récupère un numéro
int num = t_num;
++t_num;
long double x, y;
int fn = F/NB_THREAD;
int in = 0;
for (int i = 0; i < fn; ++i) {
// On tire aléatoirement x et y entre -1 et 1
x = (long double)rand()/(long double)(RAND_MAX);
y = (long double)rand()/(long double)(RAND_MAX);
if ((x*x) + (y*y) <= 1.0)
++in;
}
retvals[num] = in;
pthread_exit(0);
}
int main () {
pthread_t threads[NB_THREAD];
// Graine aléatoire avec le temps
srand(time(NULL));
// Outils pour le chronometre
struct timeval begin, end;
gettimeofday(&begin, NULL);
// Lancement des threads
for (int j = 0; j < NB_THREAD; ++j) {
if (pthread_create(&threads[j], NULL, fn_thread, NULL) != 0) {
fprintf(stderr, "Cannot create thread # %d\n", j);
return 1;
}
}
// Joining threads
for (int i = 0; i < NB_THREAD; ++i) {
pthread_join(threads[i], NULL);
}
//Summing all "in" points
int in = 0;
for (int i = 0; i < NB_THREAD; ++i) {
in += retvals[i];
}
// Calculing pi
long double pi = ((long double) in * 4.0) / (long double) F;
// Stopping timer
gettimeofday(&end, NULL);
//printf("Ratio inside / outside : %d/%d\n", in, F - in);
printf("Valeur calculée de pi : %Lf\n", pi);
printf("Nombre de thread : %d\n", NB_THREAD);
printf("Nombre de point : %d\n", F);
printf("Time: %ld microseconds\n", ((end.tv_sec - begin.tv_sec)*1000000L + end.tv_usec) - begin.tv_usec);
return 0;
}