Skip to content

Instantly share code, notes, and snippets.

@aviddiviner
Last active December 27, 2015 10:59
Show Gist options
  • Save aviddiviner/7315110 to your computer and use it in GitHub Desktop.
Save aviddiviner/7315110 to your computer and use it in GitHub Desktop.
A simple thread pool for running N parallel jobs
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