1

This is surprising for me.

static int ret = 50;
void * thread_func(void *arg)
{
    pthread_exit(&ret);
}

int main(void)
{
    pthread_t thr;
    int *exit_status;
    pthread_create(&thr, NULL, thread_func, NULL);
    sleep(2);
    pthread_join(thr, (void **)&exit_status);
    printf("value of exit status - %d\n", *exit_status);

    ret = 20;
    pthread_join(thr, (void **)&exit_status);
    printf("value of exit status - %d\n", *exit_status);
    return 0;
}

The output is

value of exit status - 50
value of exit status - 20

I was expecting both the times the exit_status would be the actual exit value(50 in my case) of the thread. Instead it is just returning the value of the global variable which I used for pthread_exit. Is it not a bug?

Sandeep
  • 18,356
  • 16
  • 68
  • 108
  • 1
    I'd say the 2nd call to `pthread_join()` provokes undefined behaviour, or at least fail. You might like to check the values returned by "system" calls. See the *Rationale Section* here: http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_join.html – alk Aug 21 '14 at 05:22

1 Answers1

1

Q: What would you return if you wanted to specify how to get the current value of ret.

A: The address of ret.

Q: What do you return?

A: The address of `ret.

Q: So what does the caller get when they dereference it?

A: The current value of ret.

You probably want pthread_exit(ret); -- returning the value of ret, and corresponding changes in the code that calls pthread_join.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278