Last active
October 5, 2015 06:08
-
-
Save Antti/2761109 to your computer and use it in GitHub Desktop.
Threadpool
This file contains hidden or 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
| 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