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.
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.
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
wait
for a thread. The
only performance benefit is that when a detached thread terminates, its resources
can be released immediately instead of having to wait for the thread to be
joined before the resources can be released.ESRCH - error search
Error searching pid/pid group.
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
:
pid > 0: Waits for the child whose process ID equals the pid passed in
pid = 0 Waits for any child whose process group ID equals that of the calling process.
pid = - 1 Waits for any child process (the default if no pid is given).