Reputation: 123
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
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
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