Note: I have removed all required error checking in the following snippet.
...
void *thread_function(void *arg)
{
...
pthread_exit("Hello");
}
pthread_t a_thread;
void *thread_result;
pthread_create(&a_thread, NULL, thread_function, NULL);
pthread_join(a_thread, &thread_result);
/*
int pthread_join(pthread_t th, void **thread_return);
The second argument is a pointer to a pointer that itself points to the return
value from the thread.
int pthread_exit(void *retval);
This function terminates the calling thread, returning a pointer to an object which
cannot be a local variable.
*/
Question: how does pthread_join populate the variable of thread_result?
Since the variable thread_result has no allocated space to hold information,
if pthread_join allocates space for thread_result, then major thread must
deallocate the resource holding by the varable. As you can see, the code doesn’t
include the deallocation resource of thread_result. So I assume that pthread_join
in fact doesn’t allocate space for thread_result.
Now the new question is how the variable thread_result can contain information without
being allocated any space?
//Update-1: Add the definition of pthread_exit.
//Update-2: Add the definition of thread_function.
Your conclusion is correct:
pthread_joindoesn’t allocate memory for the result.In fact, what happens is quite simple:
pthread_exitis provided a (void*) pointer to the result by the thread itself; it’s up to the thread to decide where this pointer comes from.pthread_join— called from another thread — stores that pointer in the variable pointed to by its second argument.As far as the result is concerned, all that
pthreadsis doing is passing a pointer across thread boundaries. It is up to the application to ensure that the pointed-to memory is deallocated in a manner that’s consistent with how it’s been allocated.