Created
November 26, 2013 14:37
-
-
Save JayH5/7659382 to your computer and use it in GitHub Desktop.
Simple Ruby threadpool
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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