morrrowgi
morrrowgi

Reputation: 170

How to wait for all threads to complete before executing next line

I have something like below:

all_hosts.each do |hostname|   
  Thread.new {
    ...
  }
end
# next line of execution

Each of the hosts above opens its own thread and executes the commands. I want to wait for all threads to finish executing before moving onto next part of file. Is there an easy way of doing this?

Upvotes: 1

Views: 2556

Answers (2)

Stefan
Stefan

Reputation: 114248

The Thread documentation explains it:

Alternatively, you can use an array for handling multiple threads at once, like in the following example:

threads = []
threads << Thread.new { puts "Whats the big deal" }
threads << Thread.new { 3.times { puts "Threads are fun!" } }

After creating a few threads we wait for them all to finish consecutively.

threads.each { |thr| thr.join }

Applied to your code:

threads = []

all_hosts.each do |hostname|
  threads << Thread.new { ... }
end

threads.each(&:join)

# next line of execution

Upvotes: 4

falsetru
falsetru

Reputation: 369424

Use Thread#join which will wait termination of the thread.

To do that you need to save threads; so use map instead of each:

threads = all_hosts.map do |hostname|   
  Thread.new {
    # commands
  }
end

threads.each(&:join)

Upvotes: 5

Related Questions