Skip to content

Instantly share code, notes, and snippets.

@ryandotsmith
Last active December 19, 2015 10:29
Show Gist options
  • Save ryandotsmith/5940245 to your computer and use it in GitHub Desktop.
Save ryandotsmith/5940245 to your computer and use it in GitHub Desktop.
# 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment