pthread_join

Function Prototype

int pthread_join(pthread_t tid, void **rval_ptr);

Function

  1. Block until target thread terminates (exits or is canceled)
  2. Retrieve thread’s return value and store in rval_ptr
  3. Clean up thread resources (automatically makes thread detached)

Set rval_ptr to NULL if you don't need the return value

Returns EINVAL if target thread is already detached

Remarks

What if thread not joined?

  • Thread becomes a “zombie thread” - its Thread Control Block (TCB) remains in memory
  • Resources leak until process ends

What if two threads try to join the same thread?

  • Undefined behavior - results are unpredictable
  • Typically one succeeds while the other errors, but this isn’t guaranteed

Design rule: Each thread should be joined by at most one other thread

What if the calling thread is canceled?

  • pthread_join stops, but the target thread remains joinable
  • Another thread must join the target to prevent it from becoming a zombie