Skip to content

Instantly share code, notes, and snippets.

@toretore toretore/t.rb
Created Mar 10, 2016

Embed
What would you like to do?
require 'thread'
class WorkerPool
def initialize
@num = 10
@jobs = Queue.new
@results = Queue.new
@stopped = false
run
end
def <<(j)
@jobs << j
end
def run
@threads = @num.times.map do
Thread.new do
loop do
break if @stopped && @jobs.empty?
@results << @jobs.pop.call
end
end
end
end
def stop
@stopped = true
@threads.each{|t| t.run if t.alive? }
end
def join
@threads.each(&:join)
end
def value
join
@results
end
end
w = WorkerPool.new
rand(100).times{ w << ->{ sleep rand } }
w.stop
r = w.value
p r.pop until r.empty?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.