Method: Zold::ThreadPool#run

Defined in:
lib/zold/thread_pool.rb

#run(threads, set = (0..threads - 1).to_a) ⇒ Object

Run this code in many threads



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/zold/thread_pool.rb', line 42

def run(threads, set = (0..threads - 1).to_a)
  raise "Number of threads #{threads} has to be positive" unless threads.positive?
  list = set.dup
  total = [threads, set.count].min
  if total == 1
    list.each_with_index { |r, i| yield(r, i) }
  elsif total.positive?
    idx = Concurrent::AtomicFixnum.new
    mutex = Mutex.new
    latch = Concurrent::CountDownLatch.new(total)
    total.times do |i|
      add do
        Thread.current.name = "#{@title}-#{i}"
        loop do
          r = mutex.synchronize { list.pop }
          break if r.nil?
          yield(r, idx.increment - 1)
        end
      ensure
        latch.count_down
      end
    end
    latch.wait
    kill
  end
end