Last active
December 27, 2015 10:59
-
-
Save aviddiviner/7315110 to your computer and use it in GitHub Desktop.
A simple thread pool for running N parallel jobs
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 'thread' | |
# 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 | |
attr_reader :size | |
def initialize(num_threads) | |
@size = num_threads | |
@pool = [] | |
@mutex = Mutex.new | |
@cv = ConditionVariable.new | |
end | |
def next_thread | |
@mutex.synchronize do | |
@cv.wait(@mutex) while @pool.size == @size | |
@pool.push Thread.new { | |
yield | |
remove_thread(Thread.current) | |
} | |
end | |
end | |
def join | |
@mutex.synchronize do | |
@cv.wait(@mutex) while !@pool.empty? | |
@cv.broadcast | |
end | |
end | |
protected | |
def remove_thread(thread) | |
@mutex.synchronize do | |
@pool.delete(thread) | |
@cv.signal | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment