Skip to content

Instantly share code, notes, and snippets.

@JayH5
Created November 26, 2013 14:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JayH5/7659382 to your computer and use it in GitHub Desktop.
Save JayH5/7659382 to your computer and use it in GitHub Desktop.
Simple Ruby threadpool
require 'set'
require 'thread'
module Prod
# A simple thread pool for running N parallel jobs.
#
# pool = ThreadPool.new(5)
# 20.times do
# pool.next_thread{ sleep 2 }
# end
# pool.join
#
class ThreadPool
def initialize(num_threads)
@n = num_threads
@pool = Set.new
@mutex = Mutex.new
@cv = ConditionVariable.new
end
def next_thread
wait_for_opening do
@pool.add(Thread.new do
yield
remove_thread Thread.current
end)
end
end
def join
@mutex.synchronize { @cv.wait(@mutex) while !@pool.empty? }
end
protected
def wait_for_opening
@mutex.synchronize do
@cv.wait(@mutex) while @pool.size == @n
yield
end
end
def remove_thread(thread)
@mutex.synchronize do
@pool.delete thread
@cv.signal
end
end
end
end # module
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment