# A program that works jobs in newly created UNIX
# process by calling fork. The number of processes
# running at any given time is bounded by our use
# of a sized queue.

require 'thread'

# Run at most 4 UNIX processes for any given time.
@limiter = SizedQueue.new(4)

# Trivial. Could be anything.
def work(i)
  1 * i
end

10_000.times do |i|
  # If the limiter is full, then we will block until space permits.
  @limiter.enq(1)
  Thread.new do
    begin Process.wait fork {work(i)}
    # Once we are done with our work and our process has exited, 
    # we can allow another process to run.
    ensure @limiter.deq
    end
  end
end