Skip to content

Instantly share code, notes, and snippets.

@rklemme
Created January 25, 2011 10:11
Show Gist options
  • Save rklemme/794746 to your computer and use it in GitHub Desktop.
Save rklemme/794746 to your computer and use it in GitHub Desktop.
Sample work distribution across processes
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