Class: Threads

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

Overview

Threads.

Author

Yegor Bugayenko ([email protected])

Copyright

Copyright © 2018 Yegor Bugayenko

License

MIT

Instance Method Summary collapse

Constructor Details

#initialize(total = Concurrent.processor_count * 8) ⇒ Threads

Returns a new instance of Threads.



32
33
34
# File 'lib/threads.rb', line 32

def initialize(total = Concurrent.processor_count * 8)
  @total = total
end

Instance Method Details

#assert(reps = 0) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/threads.rb', line 36

def assert(reps = 0)
  done = Concurrent::AtomicFixnum.new
  cycles = 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
        begin
          yield t
        rescue StandardError => e
          puts Backtrace.new(e)
          raise e
        end
        cycles.increment
        break if cycles.value > reps
      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