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



15
16
17
18
19
20
21
22
# File 'lib/futuroscope/pool.rb', line 15

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.



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

def max_workers
  @max_workers
end

#min_workersObject

Returns the value of attribute min_workers.



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

def min_workers
  @min_workers
end

#workersObject (readonly)

Returns the value of attribute workers.



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

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



38
39
40
41
42
43
# File 'lib/futuroscope/pool.rb', line 38

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.



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

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



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

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