Created
February 10, 2017 17:48
-
-
Save PatrickTulskie/98f5076cb01feffece9edf2c3d6c3b4d to your computer and use it in GitHub Desktop.
Quick and dirty thread pool
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
class Pool | |
attr_accessor :size, :jobs | |
def initialize(size: 6) | |
@size = size | |
@jobs = Queue.new | |
@pool = Array.new(@size) do |i| | |
spawn_thread(i) | |
end | |
end | |
def schedule(*args, &block) | |
@jobs << [block, args] | |
end | |
# Throw exit in each of the threads and then wait for work to finish | |
def shutdown | |
@size.times { schedule { throw :exit } } | |
self.join | |
end | |
def join | |
@pool.map(&:join) | |
end | |
def block | |
while @jobs.length > 0 | |
sleep 2 | |
end | |
end | |
private | |
def spawn_thread(id) | |
Thread.new do | |
Thread.current[:id] = id | |
catch(:exit) do | |
loop do | |
job, args = @jobs.pop | |
job.call(*args) | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment