class Futuroscope::Pool
Futuroscope's pool is design to control concurency and keep it between some certain benefits. Moreover, we warm up the threads beforehand so we don't have to spin them up each time a future is created.
Attributes
max_workers[RW]
min_workers[RW]
workers[R]
Public Class Methods
new(range = 8..16)
click to toggle source
Public: Initializes a new Pool
.
thread_count - The number of workers that this pool is gonna have
# File lib/futuroscope/pool.rb, line 16 def initialize(range = 8..16) @min_workers = range.min @max_workers = range.max @queue = Queue.new @workers = Set.new @mutex = Mutex.new warm_up_workers end
Public Instance Methods
min_workers=(count)
click to toggle source
# File lib/futuroscope/pool.rb, line 56 def min_workers=(count) @min_workers = count warm_up_workers end
pop()
click to toggle source
Public: Pops a new job from the pool. It will return nil if there's enough workers in the pool to take care of it.
Returns a Future
# File lib/futuroscope/pool.rb, line 39 def pop @mutex.synchronize do return nil if @queue.empty? && more_workers_than_needed? end return @queue.pop end
queue(future)
click to toggle source
worker_died(worker)
click to toggle source
Private: Notifies that a worker just died so it can be removed from the pool.
worker - A Worker
# File lib/futuroscope/pool.rb, line 50 def worker_died(worker) @mutex.synchronize do @workers.delete(worker) end end
Private Instance Methods
can_spin_extra_workers?()
click to toggle source
# File lib/futuroscope/pool.rb, line 71 def can_spin_extra_workers? @workers.length < @max_workers && span_chance end
finalize()
click to toggle source
# File lib/futuroscope/pool.rb, line 89 def finalize @workers.each(&:stop) end
more_workers_than_needed?()
click to toggle source
# File lib/futuroscope/pool.rb, line 79 def more_workers_than_needed? @workers.length > @min_workers end
span_chance()
click to toggle source
# File lib/futuroscope/pool.rb, line 75 def span_chance [true, false].sample end
spin_worker()
click to toggle source
# File lib/futuroscope/pool.rb, line 83 def spin_worker worker = Worker.new(self) @workers << worker worker.run end
warm_up_workers()
click to toggle source
# File lib/futuroscope/pool.rb, line 63 def warm_up_workers @mutex.synchronize do while(@workers.length < @min_workers) do spin_worker end end end