Skip to content

Instantly share code, notes, and snippets.

@oisin
Created October 30, 2014 08:58
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 oisin/68e6eb255f98bc79ca3e to your computer and use it in GitHub Desktop.
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/
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