I am checking the behavior of 'pthread_join' and have the following code:
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <errno.h>
#include <pthread.h>
void *thread(void *vargp)
{
pthread_detach(pthread_self());
pthread_exit((void *)42);
}
int main()
{
int i = 1;
pthread_t tid;
pthread_create(&tid, NULL, thread, NULL);
sleep(1);
pthread_join(tid, (void **)&i);
printf("%d\n", i);
printf("%d\n", errno);
}
Observed output on my platform (Linux 3.2.0-32-generic #51-Ubuntu SMP x86_64 GNU/Linux):
with the 'sleep(1)' commented out: 42 0
with the sleep statement, it produces: 1 0
according to the man page of pthread_join, we should get the error 'EINVAL' when we are trying to join a non-joinable thread, however, neither cases above got the errno set. And also in the first case, it seemed that we can even get the exit status of a detached thread, I am confused with the result. Could anyone explain this? Thanks
[EDIT]: I realized that the first printf may reset 'errno', however, even after I swapped the order of the two 'printf' statements, I still got the same results.