-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquestion6efficace.c
96 lines (67 loc) · 1.79 KB
/
question6efficace.c
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
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <math.h>
#include <pthread.h>
/*-------------------------------------------ATTRIBUTS------------------------------------------*/
uint64_t nb;
FILE * file;
char str[60];
pthread_t thread0;
pthread_t thread1;
//Gérer l'accès critique au file
pthread_mutex_t lock;
/*--------------------------------------DECLARATION METHODES------------------------------------*/
void* thread_prime_factors(void * u);
void print_prime_factors(uint64_t n);
/*--------------------------------------------METHODES-----------------------------------------*/
void* thread_prime_factors(void * u)
{
pthread_mutex_lock(&lock);
while ( fgets(str, 60, file)!=NULL )
{
nb=atol(str);
pthread_mutex_unlock(&lock);
print_prime_factors(nb);
pthread_mutex_lock(&lock);
}
pthread_mutex_unlock(&lock);
return NULL;
}
void print_prime_factors(uint64_t n)
{
printf("%ju : ", n );
uint64_t i;
for( i=2; n!=1 ; i++ )
{
while (n%i==0)
{
// Tant que i est un facteur premier de n
n=n/i;
printf("%ju ", i);
}
}
//On a fini !
printf("\n");
return;
}
int main(void)
{
printf("En déplaçant la boucle de lecture dans chacun des threads :\n");
file = fopen ("fileQuestion4pasEfficace.txt","r");
if (pthread_mutex_init(&lock, NULL) != 0)
{
printf("\n mutex init failed\n");
return 1;
}
//Attention en C l'appel des méthode est synchrone donc il faut d'abord créer un thread
//avant d'appeler des fonctions dans le main
pthread_create(&thread0, NULL, thread_prime_factors, NULL);
pthread_create(&thread1, NULL, thread_prime_factors, NULL);
//Wait for the thread0 to be done
pthread_join(thread0, NULL);
pthread_join(thread1, NULL);
pthread_mutex_destroy(&lock);
return 0;
}