Skip to content

Instantly share code, notes, and snippets.

@bcobb
Created November 26, 2013 21:37
Show Gist options
  • Save bcobb/7666708 to your computer and use it in GitHub Desktop.
Save bcobb/7666708 to your computer and use it in GitHub Desktop.
A small, probably bad Thread Pool written in the service of reproducing a bug.
require 'thread'
module ThreadPool
class Executor
def initialize(queue)
@queue = queue
@thread = nil
end
def start
@thread = Thread.tap { |t| t.abort_on_exception = true }.new do
loop do
@queue.shift.call
end
end
end
def stop
@thread.exit if @thread
end
end
class Pool
def initialize(limit)
@queue = Queue.new
@limit = limit
@executors = limit.times.map { Executor.new(@queue).tap(&:start) }
end
def execute(&block)
loop do
if full?
# Disclaimer: I don't know if this how one is supposed to use Thread.pass, but it seems right, based on the docs.
Thread.pass
else
break
end
end
@queue.push(block)
end
def size
@queue.size
end
def empty?
size == 0
end
def full?
size >= @limit
end
def stop
@executors.each(&:stop)
end
end
end
pool = ThreadPool::Pool.new(10)
100.times do
pool.execute do
# do something!
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment