class Threads

Threads.

Author

Yegor Bugayenko (yegor256@gmail.com)

Copyright

Copyright © 2018 Yegor Bugayenko

License

MIT

Public Class Methods

new(total = Concurrent.processor_count * 8, log: STDOUT) click to toggle source
# File lib/threads.rb, line 33
def initialize(total = Concurrent.processor_count * 8, log: STDOUT)
  raise "Total can't be nil" if total.nil?
  raise "Total can't be negative or zero: #{total}" unless total.positive?
  @total = total
  raise "Log can't be nil" if log.nil?
  @log = log
end

Public Instance Methods

assert(reps = @total) { |t, r - 1| ... } click to toggle source
# File lib/threads.rb, line 41
def assert(reps = @total)
  if reps < @total
    raise "Repetition counter #{reps} can't be smaller than #{@total}"
  end
  done = Concurrent::AtomicFixnum.new
  rep = Concurrent::AtomicFixnum.new
  pool = Concurrent::FixedThreadPool.new(@total)
  latch = Concurrent::CountDownLatch.new(1)
  @total.times do |t|
    pool.post do
      Thread.current.name = "assert-thread-#{t}"
      latch.wait(10)
      loop do
        r = rep.increment
        break if r > reps
        begin
          yield(t, r - 1)
        rescue StandardError => e
          print(Backtrace.new(e))
          raise e
        end
      end
      done.increment
    end
  end
  latch.count_down
  pool.shutdown
  raise "Can't stop the pool" unless pool.wait_for_termination(30)
  return if done.value == @total
  raise "Only #{done.value} out of #{@total} threads completed successfully"
end

Private Instance Methods

print(msg) click to toggle source