Un seul thread fonctionnant dans un programme multithreadé (avec threads dans thread)
Bonjour,
Je rencontre un problème lors de l'éxecution de mon programme multithreadé. Donc en fait j'ai une boucle for qui créée n threads et ensuite ces n threads créés chacun 2 nouveaux threads. Finalement, j'ai donc 2*n threads qui doivent fonctionner en même temps.
Je peux voir dans mon programme que les n couples de threads sont bien créés, mais aussi qu'après leurs créations que seulement le dernier thread créé tourne. Les n-1 premiers couples de threads font rien et reste bloqués.
J'ajoute que mon programme est supposé tourné à l'infini (while(1) pour l'envoi et la réception de messages dans les threads 1 et 2) et donc que les n threads créés dans la boucle for ne doivent jamais se terminer normalement.
Voici à quoi ressemble mon code :
Code:
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
|
void *thread1_send (void * arg_threads)
{
// do some work
pthread_exit (0);
}
void *thread2_listen (void * arg_threads)
{
// do some work
pthread_exit (0);
}
void *thread_multi (void * arg_threads)
{
// first thread
if (pthread_create (&th1, NULL, thread1_send, arg_threads) < 0) {
printf ("Error pthread_create for thread 1\n");
exit (1);
}
//second thread
if (pthread_create (&th2, NULL, thread2_listen, arg_threads) < 0) {
printf ("Error pthread_create for thread 2\n");
exit (1);
}
(void)pthread_join (th1, &ret_t);
(void)pthread_join (th2, &ret_t);
pthread_exit(0);
}
pthread_t * th_multi = (pthread_t *) malloc( n * sizeof(*th_multi) );
....
....
// for loop in a function
for(int i=0; i<n; i++)
{
// creation of n threads
if (pthread_create (&th_multi[i], NULL, thread_multi, arg_threads) < 0) {
printf ("Error pthread_create for thread_multi [%d].\n", i);
exit (1);
}
}
for(int j=0; j<n; j++)
{
(void)pthread_join (th_multi[j], &ret_t);
} |