Pthread: attach selected thread does not install errno correctly

I check 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 query "sleep (1)": 42 0

  • with a sleep operator, it produces: 1 0

according to the pthread_join man page, we should get an “ EINVAL ” error when we try to join a non-joinable thread, however, none of the above cases got an errno set. And also in the first case, it seemed that we can even get the exit status of a separate stream, I'm confused by the result. Can anyone explain this? Thanks

[EDIT]: I realized that the first printf can reset 'errno', however, even after I changed the order of the two printf statements, I still have the same results.

+3
source share
2 answers

Your expectation is wrong. Calling pthread_join in a separate thread causes undefined behavior. There is no requirement to set errno , return an error code, or even return at all.

If you need a quote,

The behavior is undefined if the value specified by the thread argument for pthread_join () is not a join.

Source: http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_join.html

Also note that most pthread functions, including pthread_join , do not use errno . Instead, they return an error code as the return value. Thus, the errno check after calling the pthread function is incorrect even if you did not call undefined behavior when you called it.

+5
source

You get this error while reading the return value of the pthread_join function, try the following:

 if (errno = pthread_join(tid,NULL)) { printf("An error ocurred: %i", errno); } 
0
source

All Articles