Skip to content

Instantly share code, notes, and snippets.

@toretore
Created March 10, 2016 06:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save toretore/fd4ff547ad10493bdcfa to your computer and use it in GitHub Desktop.
Save toretore/fd4ff547ad10493bdcfa to your computer and use it in GitHub Desktop.
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