Home > OS >  Ruby Thread. why "#Join"?
Ruby Thread. why "#Join"?

Time:02-20

This may sound dumb question. but Please guide me.

https://apidock.com/ruby/Thread/join

a = Thread.new { print "a"; }
a.join(5)

As we see here, #join method is basically, "Hey OS, Run this code block(thread), 5 seconds from now."

but where this name come from? join . why not just run?
in Java, it seems like slightly different meaning.

CodePudding user response:

Not quite. join is the traditional name for the operation that waits for a thread to complete. Execution "splits" when you start a thread, and "joins" when a parent becomes aware of a thread's completion.

a.join(5) doesn't say "run this thread 5 seconds from now", it says "wait up to 5 seconds for this thread to finish". It starts running as soon as you create it.

CodePudding user response:

Thread.new starts the thread. You can do a simple test:

Thread.new { puts "started" };
sleep 1
puts "done"

It will print started immediately, then wait a second, then print done.

Or run Thread.new in irb and see it execute immediately.

You need a.join because without it the main program might exit and kill the threads before the thread is complete. For example...

Thread.new do
  puts "start"

  # Simulate the thread doing some work
  sleep 1

  puts "end"
end
sleep 0.5

This will print start and that's it. The main program will end and kill the thread. The main process needs to wait until the thread is complete with join.

It's called "join" because you are joining the thread back together with the main thread which spawned it.

  • Related