pthread_join and pthread_exit

537 views Asked by At
int pthread_join(pthread_t thread, void **retval);
void pthread_exit(void *retval);

in the pthread_exit call we are passing a pointer to the value we have to pass.And in pthread_join it should be a pointer to pointer according to the man page.I am not convinced with it.when i use pointer to a char ,i am getting the expected result.But when i use a int as shown below i am getting a garbage value.is this implementation correct ?

void * sum(void * id)
{
      int n = *(int *)id;
      pthread_exit((void *)&n);
}
void main()
{
      pthread_t t1;
      int *s;
      s = malloc(sizeof(int));
      int num;
      num=5;
      pthread_create(&t1,NULL,sum,(void *)&num);
      pthread_join(t1,(void **)&s);
      printf("returned %d \n",*s);
      pthread_exit(NULL);
}
1

There are 1 answers

0
Tomo On BEST ANSWER

Don't return values from the stack. From the man page on pthread_exit:

The value pointed to by  retval  should  not  be  located  on  the  calling
thread's  stack,  since  the contents of that stack are undefined after the
thread terminates.