A thread runs work independently, and join waits for it to finish.

thread join `Thread.new` starts a block on another Ruby thread. `join` keeps the main code from reading the result too early.

Thread Join

work_units
thread_join.rb
Replay: real traced execution (multi-file project)
work_units = 3
result = 0

worker = Thread.new do
  subtotal = work_units * 10
  result = subtotal + 1
end

worker.join

puts "work_units=#{work_units}"
puts "result=#{result}"
puts "worker_done=#{!worker.alive?}"
work_units = 2
result = 0

worker = Thread.new do
  subtotal = work_units * 10
  result = subtotal + 1
end

worker.join

puts "work_units=#{work_units}"
puts "result=#{result}"
puts "worker_done=#{!worker.alive?}"
work_units = 4
result = 0

worker = Thread.new do
  subtotal = work_units * 10
  result = subtotal + 1
end

worker.join

puts "work_units=#{work_units}"
puts "result=#{result}"
puts "worker_done=#{!worker.alive?}"
  1. work_units ← 3, result ← 0, worker ← ⟨Thread A /tmp/execution/⟨tmp B⟩.rb:41 run⟩

    1work_units→ 3 = 3  #@work_units=2, 42result→ 0 = 034worker→ ⟨Thread A /tmp/execution/⟨tmp B⟩.rb:41 run⟩ = Thread.new do5  subtotal = work_units * 106  result = subtotal + 17end
  2. subtotal ← 30

    4worker = Thread.new do5  subtotal→ 30 = work_units3 * 106  result = subtotal30 + 17end
  3. puts "work_units=#{work_units}"

    11puts "work_units=#{work_units3}"12puts "result=#{result31}"13puts "worker_done=#{!worker.alive?false}"
    outputwork_units=3
    result=31
    worker_done=true
  1. work_units ← 2, result ← 0, worker ← ⟨Thread A /tmp/execution/⟨tmp B⟩.rb:41 run⟩

    1work_units→ 2 = 22result→ 0 = 034worker→ ⟨Thread A /tmp/execution/⟨tmp B⟩.rb:41 run⟩ = Thread.new do5  subtotal = work_units * 106  result = subtotal + 17end
  2. subtotal ← 20

    4worker = Thread.new do5  subtotal→ 20 = work_units2 * 106  result = subtotal20 + 17end
  3. puts "work_units=#{work_units}"

    11puts "work_units=#{work_units2}"12puts "result=#{result21}"13puts "worker_done=#{!worker.alive?false}"
    outputwork_units=2
    result=21
    worker_done=true
  1. work_units ← 4, result ← 0, worker ← ⟨Thread A /tmp/execution/⟨tmp B⟩.rb:41 run⟩

    1work_units→ 4 = 42result→ 0 = 034worker→ ⟨Thread A /tmp/execution/⟨tmp B⟩.rb:41 run⟩ = Thread.new do5  subtotal = work_units * 106  result = subtotal + 17end
  2. subtotal ← 40

    4worker = Thread.new do5  subtotal→ 40 = work_units4 * 106  result = subtotal40 + 17end
  3. puts "work_units=#{work_units}"

    11puts "work_units=#{work_units4}"12puts "result=#{result41}"13puts "worker_done=#{!worker.alive?false}"
    outputwork_units=4
    result=41
    worker_done=true