Skip to content

Instantly share code, notes, and snippets.

@glebtv
Forked from rklemme/work.rb
Created December 4, 2013 15:47
Show Gist options
  • Save glebtv/7789816 to your computer and use it in GitHub Desktop.
Save glebtv/7789816 to your computer and use it in GitHub Desktop.
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