Created
October 7, 2009 13:54
-
-
Save jimeh/204035 to your computer and use it in GitHub Desktop.
Ruby: #call_parallel
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# 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