Class: WorkersPool

Inherits:
Object
  • Object
show all
Defined in:
lib/itubib/workers_pool.rb

Overview

Workers poll.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(num_workers = 2) ⇒ WorkersPool

Returns a new instance of WorkersPool.



7
8
9
10
11
12
# File 'lib/itubib/workers_pool.rb', line 7

def initialize(num_workers = 2)
  @num_workers = num_workers < 2 ? 2 : num_workers
  @queue = SizedQueue.new(num_workers * 2)
  @result = []
  @nb_hits = 0
end

Instance Attribute Details

#nb_hitsObject

Returns the value of attribute nb_hits.



5
6
7
# File 'lib/itubib/workers_pool.rb', line 5

def nb_hits
  @nb_hits
end

Instance Method Details

#<<(item) ⇒ Object



29
30
31
32
# File 'lib/itubib/workers_pool.rb', line 29

def <<(item)
  @queue << item
  self
end

#endObject



34
35
36
# File 'lib/itubib/workers_pool.rb', line 34

def end
  @num_workers.times { @queue << :END }
end

#resultObject



24
25
26
27
# File 'lib/itubib/workers_pool.rb', line 24

def result
  @threads.each(&:join)
  @result
end

#sizeObject



38
39
40
# File 'lib/itubib/workers_pool.rb', line 38

def size
  @result.size
end

#worker(&block) ⇒ Object



14
15
16
17
18
19
20
21
22
# File 'lib/itubib/workers_pool.rb', line 14

def worker(&block)
  @threads = Array.new @num_workers do
    Thread.new do
      until (item = @queue.pop) == :END
        @result << yield(item) if block
      end
    end
  end
end