user3358302
user3358302

Reputation: 2111

ruby threading output

I'm trying this example:

10.times do
  Thread.new do
    greeting_message = "Hello World ruby !"
    puts "#{greeting_message}
  end
end

I tried running this multiple times, and sometimes it puts once:

 Hello World ruby ! ruby basic_threadding_ruby.rb  0.05s user 0.04s system 97% cpu 0.096 total

other times its twice, sometimes its the full 10 times.

This inconsistency is making me confused. Is there a reason why Hello World ruby ! is printed only once? I thought when you run a ruby script, it waits until all threads/processes are done before terminating and returning.

Upvotes: 2

Views: 609

Answers (1)

Ry-
Ry-

Reputation: 224887

I thought when you run a ruby script, it waits until all threads/processes are done before terminating and returning?

Nope! From the documentation for Thread:

If we don't call thr.join before the main thread terminates, then all other threads including thr will be killed.

So you’ll need to join all of them:

threads = 10.times.map do
  Thread.new do
    puts 'Hello, Ruby!'
  end
end

threads.each &:join

Upvotes: 2

Related Questions