Sobes.tech
Middle

What does the join method do in the Thread class in Ruby?

sobes.tech AI

Answer from AI

The join method in the Thread class in Ruby blocks the execution of the current thread until the thread on which join is called completes its execution (or throws an exception).

Main aspects:

  • Synchronization: Used to synchronize threads, ensuring that certain code is not executed until the background thread finishes.
  • Return value: The join method returns the thread object on which it was called.
  • Timeout (optional): Can accept an optional argument - a timeout in seconds. If the thread does not finish within the specified time, join returns false. Without a timeout, join waits indefinitely.
# Example of using join
thread = Thread.new do
  sleep 2
  puts "Thread has finished"
end

puts "Waiting for thread to finish..."
thread.join # Blocks the current thread until thread finishes
puts "Thread has finished, continuing execution"

# Example with timeout
thread_with_timeout = Thread.new do
  sleep 5
  puts "Thread with timeout has finished"
end

puts "Waiting for thread with timeout..."
if !thread_with_timeout.join(2)
  puts "Thread did not finish within 2 seconds"
else
  puts "Thread finished within 2 seconds"
end