Skip to content

Instantly share code, notes, and snippets.

@Antti
Last active October 5, 2015 06:08
Show Gist options
  • Select an option

  • Save Antti/2761109 to your computer and use it in GitHub Desktop.

Select an option

Save Antti/2761109 to your computer and use it in GitHub Desktop.
Threadpool
class ThreadPool
def initialize(size)
@size = size
@queue = Queue.new
@pool = Array.new(@size) do |i|
Thread.new do
Thread.current.abort_on_exception = true
Thread.current[:id] = i
catch(:exit) do
loop do
job, args = @queue.pop
job.call(*args)
end
end
end
end
end
def schedule(*args, &block)
@queue.push([block, args])
end
def inspect
"#{self.class}<Queue size: #{@queue.size}>"
end
def shutdown
@size.times do
schedule { throw :exit }
end
wait
end
private
def wait
@pool.map(&:join)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment