Last active
April 12, 2018 16:24
-
-
Save havenwood/93df890b1991aedb3164885e1b767429 to your computer and use it in GitHub Desktop.
A thread pool for mikhael_k33hl's #ruby irc use case
This file contains 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
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