1

I am learning how to use <pthread.h>, and the textbook says that:

The pthread_join function blocks the calling thread ...

But in my test, it didn't:

void *a_thread(void *pt) {
  puts("a_thread:join");
  pthread_join(*(pthread_t *)pt, NULL); // <-- a_thread didn't wait for
  puts("a_thread:joined");              //     itself to finish executing.

  return NULL;
}

int main(void) {
  pthread_t t;

  puts("create");
  pthread_create(&t, NULL, a_thread, &t);
  puts("created");

  puts("main:join");
  pthread_join(t, NULL);
  puts("main:joined");
}

gcc -Og -o test test.c; ./test:

create
created
main:join
a_thread:join
a_thread:joined
main:joined
shynur
  • 334
  • 10
  • 1
    The main thread was blocked until the child thread terminated. A thread should not try to join itself. Most likely, the call to `pthread_join()` in the thread function failed; formally, it invoked undefined behaviour. The specification of [`pthread_join()`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_join.html) says (in part): _The behavior is undefined if the value specified by the thread argument to `pthread_join()` refers to the calling thread._. You don't check that any of the function calls are successful, which is dangerous. – Jonathan Leffler Apr 07 '23 at 15:26
  • @JonathanLeffler: Thanks, you're right. I should always check its return value. I just tested it again, and the return value is 35. – shynur Apr 07 '23 at 15:30
  • 1
    @Shynur On your system, error 35 is `EDEADLK`, which pthreads [documents](https://man7.org/linux/man-pages/man3/pthread_join.3.html) as: "*`EDEADLK` A deadlock was detected (e.g., two threads tried to join with each other); **or `thread` specifies the calling thread**.*" – Remy Lebeau Apr 07 '23 at 16:43

1 Answers1

2

From the pthread_join man page:

If multiple threads simultaneously try to join with the same thread, the results are undefined.

Here you have the worker thread and the main thread both trying to join on the worker thread, sounds like UB to me.

yano
  • 4,827
  • 2
  • 23
  • 35
  • 2
    Note that a thread trying to join itself is also undefined behaviour — but that's what the child thread tried to do. See my [comment](https://stackoverflow.com/questions/75959603/why-pthread-join-didnt-block-its-calling-thread#comment133975144_75959603) to the main question for more information. The Linux man page you link to says that one of the errors is `EDEADLK — A deadlock was detected (e.g., two threads tried to join with each other); or thread specifies the calling thread.`. The OP's response to my comment indicates that EDEADLK was returned. – Jonathan Leffler Apr 07 '23 at 16:28