-
-
Save glebtv/7789816 to your computer and use it in GitHub Desktop.
This file contains 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
require 'set' | |
LOCK = Mutex.new | |
num = Integer(ARGV.shift || 4) | |
processes = Set.new | |
Signal.trap "INT" do |s| | |
$stderr.puts "Shutdown" | |
LOCK.synchronize do | |
num = 0 # prevent further | |
processes.each do |pid| | |
Process.kill "TERM", pid rescue nil | |
end | |
end | |
Process.waitall # optional | |
exit 0 | |
end | |
catch :exit do | |
loop do | |
LOCK.synchronize do | |
throw :exit if num == 0 | |
while processes.size < num | |
child = fork do | |
Signal.trap "INT", "EXIT" | |
5.times {|i| puts "Working in #$$ step #{i}"; sleep(1+ rand(3)) } | |
end | |
processes.add child | |
end | |
end | |
pid = Process.wait | |
LOCK.synchronize do | |
processes.delete pid | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment