rubynewbie
rubynewbie

Reputation: 123

Ruby: Thread doesn't run

I'm learning Threads in Ruby.

I created a thread but it doesn't work. How can I fix it?

puts 'start'
Thread.new do
  puts 'thread'
  10.times { |i| puts i  }
end

puts 'start 2'

Output:

start
start 2

Upvotes: 1

Views: 171

Answers (2)

Lane
Lane

Reputation: 695

try

puts 'start'

t = Thread.new do
  puts 'thread'
  10.times { |i| puts i  }
end

t.join

puts 'start 2'

or

puts 'start'

Thread.new do
  puts 'thread'
  10.times { |i| puts i  }
end.join

puts 'start 2'

Upvotes: 0

ndnenkov
ndnenkov

Reputation: 36100

The problem is that the main thread ends without the other thread executing. You have to make the main thread wait for it to finish using Thread#join:

puts 'start'
Thread.new do
  puts 'thread'
  10.times { |i| puts i  }
end.join

puts 'start 2'

Upvotes: 4

Related Questions