Skip to content

Instantly share code, notes, and snippets.

@jimeh
Created October 7, 2009 13:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jimeh/204035 to your computer and use it in GitHub Desktop.
Save jimeh/204035 to your computer and use it in GitHub Desktop.
Ruby: #call_parallel
#
# Run multiple system commands in parallel
#
def call_parallel(cmds = [], check_interval = nil)
if cmds.size > 0
threads, results = [], []
cmds.each do |cmd|
threads << Thread.new { results << [cmd, `#{cmd}`, $?] }
end
is_done = false
check_interval = 0.2 if check_interval.nil?
while is_done == false do
sleep check_interval
done = true
threads.each { |thread| done = false if thread.status != false }
is_done = true if done
end
yield(results)
end
end
#
# Example usage
#
cmds = [ "lsof | grep ruby", "echo 'hello world'" ]
call_parallel(cmds) do |results|
results.each do |result|
puts "------------------------------------------"
puts " Command: #{result[0]}"
puts " Exit code: #{result[2].to_i}"
puts " Output: "
puts "#{result[1]}"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment