Class: ThreadPool

Inherits:
Object
  • Object
show all
Defined in:
lib/nswtopo/helpers/thread_pool.rb

Constant Summary collapse

CORES =
Etc.nprocessors rescue 1

Instance Method Summary collapse

Constructor Details

#initialize(size = CORES) ⇒ ThreadPool

Returns a new instance of ThreadPool.



4
5
6
# File 'lib/nswtopo/helpers/thread_pool.rb', line 4

def initialize(size = CORES)
  @args, @size = [], size
end

Instance Method Details

#<<(args) ⇒ Object



8
9
10
# File 'lib/nswtopo/helpers/thread_pool.rb', line 8

def <<(args)
  tap { @args << args }
end

#each(&block) ⇒ Object



22
23
24
25
26
27
28
# File 'lib/nswtopo/helpers/thread_pool.rb', line 22

def each(&block)
  queue = Queue.new
  threads(queue, &block).tap do
    @args.inject(queue, &:<<).close
  end.each(&:join)
  @args
end

#in_groups(&block) ⇒ Object



30
31
32
33
34
35
36
37
38
# File 'lib/nswtopo/helpers/thread_pool.rb', line 30

def in_groups(&block)
  queue = Queue.new
  threads(queue, &block).tap do
    @args.group_by.with_index do |args, index|
      index % @size
    end.values.inject(queue, &:<<).close
  end.each(&:join)
  @args
end

#threads(queue, &block) ⇒ Object



12
13
14
15
16
17
18
19
20
# File 'lib/nswtopo/helpers/thread_pool.rb', line 12

def threads(queue, &block)
  @size.times.map do
    Thread.new do
      while args = queue.pop
        block.call(*args)
      end
    end
  end
end