Bonsoir,
J'essaye de comprendre le fonctionnement des threads, je me suis inspiré du programme d'exemple de la page man pthread_create pour écrire un petit code afin de tester différentes fonctions, j'ai un problème avec la valeur de retour (voir le code et la sortie du programme ci dessous), le retour du thread[0] n'est jamais bon alors que les suivants oui ! de plus si je demande 10 thread j'ai une erreur de segmentation, sinon j'ai un "abandon" ??? après le retour de thread[4] !
Votre aide serai la bien venue, merci.
Code:#include<stdio.h> #include<unistd.h> #include<pthread.h> #include <sys/syscall.h> typedef struct { pthread_t thread_id; int thread_num; }ThreadInfo; void *fx(void *arg) { ThreadInfo *thread_info = (ThreadInfo *) arg; thread_info->thread_id=syscall(SYS_gettid); printf("fx : new thread[%i] : %i\n",thread_info->thread_num, thread_info->thread_id); sleep(thread_info->thread_num*2+5); printf("fx : thread[%i] : end !\n",thread_info->thread_num); char s[256]; sprintf(s,"thread[%i] sleep time : %i",thread_info->thread_num,thread_info->thread_num*2+5); return &s; } int main() { int i,n; printf("Numbers of threads ?\n"); if( (scanf("%i",&n))!=1){printf("scanf error ! \n");return -1;} pthread_t *thread; thread=malloc(sizeof(thread)*n); ThreadInfo *thread_info; thread_info=malloc(sizeof(thread_info)*n); pthread_attr_t thread_attr; for(i=0;i<n;i++) { thread_info[i].thread_id=0; thread_info[i].thread_num=i; if( (pthread_attr_init(&thread_attr))!=0 ){perror("create thread attributes error");return -1;} if( (pthread_create(&thread[i],&thread_attr,&fx,&thread_info[i]))!=0 ){perror("create thread error");return -1;} while(thread_info[i].thread_id==0); printf("main : create thread[%i] : %i\n",i,thread_info[i].thread_id); if( (pthread_attr_destroy(&thread_attr))!=0 ){perror("destroy thread attributes error");return -1;} } void *res; for(i=0;i<n;i++) { res=NULL; if( (pthread_join(thread[i], &res))!=0 ){perror("join thread error !\n");return -1;} printf("main : joined with thread[%i] returned value : <%s>\n",i, (char *) res); } return 0; }
sortie du programme :
Code:[doul@localhost thread]$ ./thread Numbers of threads ? 5 main : create thread[0] : 5935 fx : new thread[0] : 5935 main : create thread[1] : 5936 fx : new thread[1] : 5936 main : create thread[2] : 5937 fx : new thread[2] : 5937 main : create thread[3] : 5938 fx : new thread[3] : 5938 main : create thread[4] : 5939 fx : new thread[4] : 5939 fx : thread[0] : end ! main : joined with thread[0] returned value : <��Z��>o�> fx : thread[1] : end ! main : joined with thread[1] returned value : <thread[1] sleep time : 7> fx : thread[2] : end ! main : joined with thread[2] returned value : <thread[2] sleep time : 9> fx : thread[3] : end ! main : joined with thread[3] returned value : <thread[3] sleep time : 11> fx : thread[4] : end ! Abandon [doul@localhost thread]$
-----