Wait vs (pthread )join

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the unix category.

Last Updated: 2024-11-23

Biggest difference is that join operates on threads whereas wait operates on processes.

Join

In Ruby you often see simple threaded code like this

threads = []
10.times do
  threads << Thread.new do
    do_something
  end
end
threads.each(&:join)

puts 'Done with all threads'

The effect of this is that the calling thread suspends execution and waits until each thread finishes execution at the line threads.each(&:join)

The equivalent system call is pthread_join. From its man page

The pthread_join() function suspends execution of the calling thread until
the target thread terminates unless the target thread has already
terminated.

Errors possible with join

EDEADLK - error deadlock

A deadlock was detected (e.g., two threads tried to join with each other); (Aside: for a deadlock, you need at least two locks)

EINVAL - error invalid

Thread is not a joinable thread.

Some context: There are two types of threads

ESRCH - error search

Error searching pid/pid group.

Wait

Let's start with some example code:

include Process
fork { exit 99 }                 #=> 27429
wait                             #=> 27429
$?.exitstatus

API is

def wait(pid = -1)
end

Without any arguments, wait pauses the calling / parent process until the child process finishes.

Which child it waits on depends on the value of pid:

Resources