[ Thread argument printing garbage values ]
I was trying a simple program on threads passing the arguments.
#include<stdio.h>
#include<pthread.h>
#include<malloc.h>
#define NUMTHREADS 5
typedef struct _data_t{
int data;
char* name;
}_data;
void* mythread(void* arg){
_data* mydata = (struct _data_t*) arg;
printf("\n no : %d name : %s \n",mydata->data,mydata->name);
pthread_exit(NULL);
}
int main(){
pthread_t tid[NUMTHREADS];
_data mydata;
mydata.data = 100;
mydata.name = "Netapp";
int i;
for(i=0;i<NUMTHREADS;i++){
pthread_create(&tid[i],NULL,&mythread,(void*)&mydata);
}
pthread_exit(NULL);
return 0;
}
Output :
angus@ubuntu:~/angus/thread$ ./a.out
no : 0 name : 1�I��^H��H���PTI��0@
no : 0 name : 1�I��^H��H���PTI��0@
no : 0 name : 1�I��^H��H���PTI��0@
no : 0 name : 1�I��^H��H���PTI��0@
no : 0 name : 1�I��^H��H���PTI��0@
Answer 1
When main
terminates, mydata
ceases to exist, but the threads are still running and accessing it.
You should either wait for the spawned threads to terminate before you exit main
(using pthread_join
), or define mydata
so that it outlives scope of main
.