Class: Futuroscope::Pool

Inherits:
Object
  • Object
show all
Defined in:
lib/futuroscope/pool.rb

Overview

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.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(range = 8..16) ⇒ Pool

Public: Initializes a new Pool.

thread_count - The number of workers that this pool is gonna have



16
17
18
19
20
21
22
23
# 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

Instance Attribute Details

#max_workersObject

Returns the value of attribute max_workers.



11
12
13
# File 'lib/futuroscope/pool.rb', line 11

def max_workers
  @max_workers
end

#min_workersObject

Returns the value of attribute min_workers.



11
12
13
# File 'lib/futuroscope/pool.rb', line 11

def min_workers
  @min_workers
end

#workersObject (readonly)

Returns the value of attribute workers.



10
11
12
# File 'lib/futuroscope/pool.rb', line 10

def workers
  @workers
end

Instance Method Details

#popObject

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



39
40
41
42
43
44
# 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) ⇒ Object

Public: Enqueues a new Future into the pool.

future - The Future to enqueue.



28
29
30
31
32
33
# File 'lib/futuroscope/pool.rb', line 28

def queue(future)
  @mutex.synchronize do
    spin_worker if can_spin_extra_workers?
    @queue.push future
  end
end

#worker_died(worker) ⇒ Object

Private: Notifies that a worker just died so it can be removed from the pool.

worker - A Worker



50
51
52
53
54
# File 'lib/futuroscope/pool.rb', line 50

def worker_died(worker)
  @mutex.synchronize do
    @workers.delete(worker)
  end
end