Bonsoir

je lis actuellement le chapitre 4 de ALP pour linux , ça concerne les threads , j'ai repris le code sur les nombres premiers , j'ai essayé d'ajouter un 2 ièm thread pour la recherche de premier , mais je n'arrive pas à placer mes instructions de mutex dans le bloc donc il ne se cadence pas comme il faut , sachant que 1 des 2 thread doit me renvoyer le Nième premiers et rendre le terminal derrière. Cependant quand je compile le code , le second thread n'est pas visible par les printf() , le code ne se termine pas comme il faudrait .

merci pour vos remarques .

Code : Sélectionner tout - Visualiser dans une fenêtre à part
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
 
 
#define _REENTRANT
 
#include <stdio.h>
#include <stdlib.h>
// pthread
#include <pthread.h>
 
 
 
static int candidate = 3 ;
static int n = 10 ;    /* le 10 iem premier c'est 29 */
 
static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
 
 
 
void * threadfunc ()
{
pthread_mutex_lock (&mtx);
while (1) {
 
 
int factor ;
int is_prime = 1 ;
 
 
 
for (factor = 2 ; factor * factor <= candidate ; ++factor)  /* optimisation des diviseurs */
 
   if ( candidate % factor == 0 )
        {
        is_prime = 0 ;
        break ;
        }
printf("thread_id %lu\n" ,pthread_self());
 
if (is_prime)
    {
 
        if (--n - 1 == 0)
        {
            printf(" %lu\t",pthread_self());
            return (void *)candidate  ;
            pthread_exit (0) ;
        }
    }
 
candidate += 2 ;
printf("candi %d & thread %lu\n" , candidate , pthread_self()); // on vise que les nombres impairs après 2
 
         }
 
pthread_exit (0) ;
pthread_mutex_unlock (&mtx);
}
 
 
 
int main (int argc , char * argv [] ) {
 
 
int s ;
pthread_t thread1;
pthread_t thread2;
 
 
if ((s = pthread_create ( &thread1, NULL , threadfunc , NULL)) !=0 )
        printf("error tread 1 \n");
 
if ((s = pthread_create ( &thread2, NULL , threadfunc , NULL)) !=0 )
        printf("error tread 2 \n");
 
 
 
if (( s = pthread_join ( thread1 , (void *) &candidate )) !=0 )
        printf("error join 1 \n");
 
 
 
if (( s = pthread_join ( thread2 , (void *) &candidate )) !=0 )
       printf("error join 2 \n");
 
 
printf("le nieme premier %d\n" , candidate ) ;
 
 
 
 
return (0) ;
}