Reputation: 1701
I'm trying to figure out a good way to wait for all threads to be executed before the main thread finishes.
How can I do that in the following code?
threads = []
counter = 1000
lines = 0
counter.times do |i|
puts "This is index number #{i}."
end
puts "You've just seen the normal printing and serial programming.\n\n"
counter.times do |i|
Thread.new do
some_number = Random.rand(counter)
sleep 1
puts "I'm thread number #{i}. My random number is #{some_number}.\n"
lines += 1
end
end
messaged = false
while lines < 1000
puts "\nWaiting to finish.\n" unless messaged
print '.'
puts "\n" if lines == 1000
messaged = true
end
puts "\nI've printed #{lines} lines.\n"
puts "This is end of the program."
The program puts the I'm thread number XXX. My random number is YYY mixed with the dots from the while loop almost at the end of the main thread. If I don't use the while loop, the program finishes before the threads finish.
Upvotes: 2
Views: 733
Reputation: 1602
To make the parent wait for the children to finish, you use join
threads = []
counter.times do |i|
thr = Thread.new do
some_number = Random.rand(counter)
sleep 1
puts "I'm thread number #{i}. My random number is #{some_number}.\n"
lines += 1
end
threads << thr
end
threads.each {|thread| thread.join }
Upvotes: 3
Reputation: 54984
You need to keep a reference to the threads so you can 'join' them. Something like:
counter.times.map do |i|
Thread.new do
# thread code here
end
end.each{|t| t.join}
Upvotes: 1