Last active
May 12, 2019 03:08
-
-
Save zquestz/3f072ef3bdad0d5c17fd to your computer and use it in GitHub Desktop.
threadpool
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
require 'thread' | |
class ThreadPool | |
attr_reader :queue, :threads | |
def initialize(size = 10) | |
@queue = Queue.new | |
@threads = [] | |
size.times do | |
@threads << Thread.new do | |
catch(:done) do | |
loop do | |
job, args = @queue.pop | |
job.call(*args) | |
end | |
end | |
end | |
end | |
end | |
def add(*args, &block) | |
@queue << [block, args] | |
end | |
def run | |
@threads.size.times do | |
add do | |
throw :done | |
end | |
end | |
@threads.each(&:join) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is sick! I can't believe you took 35 lines.