-
-
Save toretore/fd4ff547ad10493bdcfa to your computer and use it in GitHub Desktop.
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 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