Skip to content

Instantly share code, notes, and snippets.

@havenwood
Last active April 12, 2018 16:24
Show Gist options
  • Save havenwood/93df890b1991aedb3164885e1b767429 to your computer and use it in GitHub Desktop.
Save havenwood/93df890b1991aedb3164885e1b767429 to your computer and use it in GitHub Desktop.
A thread pool for mikhael_k33hl's #ruby irc use case
Thread.abort_on_exception = true
class ThreadPool
attr_reader :threads
attr_reader :queue
def initialize size: 10
@queue = Queue.new
@threads = Array.new size do
Thread.new do
loop do
@queue.pop.call
break if @queue.empty?
end
end
end
end
def << work
@queue << work
end
end
pool = ThreadPool.new
20.times do |n|
work = ->{ sleep 10; puts n }
pool << work
end
pool.threads.each &:join
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment