Created
October 30, 2014 08:58
-
-
Save oisin/68e6eb255f98bc79ca3e to your computer and use it in GitHub Desktop.
Simple Ruby thread pool as per http://burgestrand.se/code/ruby-thread-pool/
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
| require 'thread' | |
| module Alert | |
| def self.yikes(msg) | |
| # Use this to log/trigger monitor | |
| puts msg | |
| end | |
| end | |
| # See http://burgestrand.se/code/ruby-thread-pool/ | |
| class Pool | |
| LOW_ALERT_LIMIT = 10 | |
| HIGH_ALERT_LIMIT = 20 | |
| def initialize(size) | |
| @size = size | |
| @jobs = Queue.new | |
| @pool = Array.new(@size) do |inx| | |
| Thread.new do | |
| Thread.current[:id] = inx | |
| catch(:exit) do | |
| loop do | |
| job, args = @jobs.pop | |
| job.call(*args) | |
| end | |
| end | |
| end | |
| end | |
| end | |
| def schedule(*args, &block) | |
| @jobs << [block, args] | |
| if @jobs.length > HIGH_ALERT_LIMIT | |
| Alert.yikes("Over HIGH alert limit on queue in thread! #{Thread.current[:id]}") | |
| elsif @jobs.length > LOW_ALERT_LIMIT | |
| Alert.yikes("Over low alert limit on queue in thread #{Thread.current[:id]}") | |
| end | |
| end | |
| def shutdown | |
| @size.times do | |
| schedule { throw :exit } | |
| end | |
| @pool.map(&:join) | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment