Skip to content

Instantly share code, notes, and snippets.

@PatrickTulskie
Created February 10, 2017 17:48
Show Gist options
  • Save PatrickTulskie/98f5076cb01feffece9edf2c3d6c3b4d to your computer and use it in GitHub Desktop.
Save PatrickTulskie/98f5076cb01feffece9edf2c3d6c3b4d to your computer and use it in GitHub Desktop.
Quick and dirty thread pool
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