C'est un programme multithread très simple. Il va créer deux threads et courir. Dans le fil, il copiera le argv0
à origname
.un résultat étrange du programme pthread
Lors de la première utilisation, le origname
est correct.
Mais après être entré dans la boucle while, l'origname sera corrompu par le sprintf
.
Il imprimera comme:
Hello World! It's me, thread #0 ./multithread 3!
origname 0 ./multithread 3!
le contenu de origname
est le paramètre pour le sprintf
. Je ne comprends pas quelle est la raison. Quelqu'un peut-il aider?
#include <pthread.h>
#include <stdio.h>
#define NUM_THREADS 2
void sendstring(char *string)
{
printf("%s",string);
}
struct thread_data{
int thread_id;
char *argv0;
};
struct thread_data thread_data_array[NUM_THREADS];
void *PrintHello(void *parameter)
{
struct thread_data *childpara;
childpara = (struct thread_data *)parameter;
int i = 0;
char origname[20];
strncpy(origname, childpara->argv0,strlen(childpara->argv0));
origname[strlen(childpara->argv0)] = '\0';
printf("init origname %s argv0 %s\n",origname, childpara->argv0);
while(1)
{
printf("origname %s\n",origname);
sleep(1);
char buffer[30];
sprintf(buffer,"Hello World! It's me, thread #%ld %s %d!\n", childpara->thread_id, childpara->argv0, i++);
sendstring(buffer);
}
pthread_exit(NULL);
}
int main (int argc, char *argv[])
{
pthread_t threads[NUM_THREADS];
int rc;
long t;
for(t=0; t<NUM_THREADS; t++){
thread_data_array[t].thread_id = t;
thread_data_array[t].argv0 = argv[0];
rc = pthread_create(&threads[t], NULL, PrintHello,(void *) &thread_data_array[t]);
if (rc){
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
pthread_exit(NULL);
}
C'est ce que je veux. Je veux utiliser argv [0] comme paramètre pour le nouveau thread créé. Je pense que ce n'est pas le problème. Je copie le contenu de ce pointeur vers l'origname, mais pas le pointeur. Quand je commente le sprintf, cela fonctionne correctement. – Zhongshu
Vous devez comprendre - vous ne * copiez * pas le contenu. Vous copiez simplement le pointeur, ce qui signifie que les deux points pointent vers le même espace mémoire. Utilisez strcpy(). – riwalk
En outre, il n'y a pas de sorte de sémaphore/barrière/mutex sur la sortie, donc quand vous le faites fonctionner, la sortie des deux threads sera parfois brouillée. – riwalk