Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

why pthread_join didn't block its calling thread

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading