Skip to content

Instantly share code, notes, and snippets.

@brain64bit
Forked from rosenfeld/thread-pool.rb
Created January 30, 2018 16:13
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 brain64bit/ab417d90b058e5dc0a65d5b003c2b064 to your computer and use it in GitHub Desktop.
Save brain64bit/ab417d90b058e5dc0a65d5b003c2b064 to your computer and use it in GitHub Desktop.
Simple thread pool implementation in Ruby
require 'thread' # for Mutex: Ruby doesn't provide out of the box thread-safe arrays
class ThreadPool
def initialize(max_threads = 10)
@pool = SizedQueue.new(max_threads)
max_threads.times{ @pool << 1 }
@mutex = Mutex.new
@running_threads = []
end
def run(&block)
@pool.pop
@mutex.synchronize do
@running_threads << Thread.start do
begin
block[]
rescue Exception => e
puts "Exception: #{e.message}\n#{e.backtrace}"
ensure
@pool << 1
end
end
end
end
def await_completion
@running_threads.each &:join
end
end
pool = ThreadPool.new 5
10.times {|i| pool.run{sleep 1} }
pool.await_completion
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment