Class: Barrier
- Inherits:
-
Object
- Object
- Barrier
- Defined in:
- lib/barrier.rb
Overview
A synchronization barrier enables multiple threads to wait until all threads have all reached a particular point of execution before any thread continues.
Instance Method Summary collapse
-
#initialize(count) ⇒ Barrier
constructor
Initialize new barrier.
-
#wait ⇒ Object
The #wait function shall synchronize participating threads at the barrier.
Constructor Details
#initialize(count) ⇒ Barrier
Initialize new barrier. The count argument specifies the number of threads that must call #wait before any of them successfully return from the call. The value specified by count must be greater than zero.
For example b = Barrier.new(3) 3.times do Thread.new do print 1 b.wait print 2 end end sleep(1) puts produce 111222
25 26 27 28 29 30 |
# File 'lib/barrier.rb', line 25 def initialize(count) @count_max = count @count = 1 @mutex = Mutex.new @lock = ConditionVariable.new end |
Instance Method Details
#wait ⇒ Object
The #wait function shall synchronize participating threads at the barrier. The calling thread shall block until the required number of threads have called #wait specifying the barrier.
35 36 37 38 39 40 41 42 43 44 45 46 |
# File 'lib/barrier.rb', line 35 def wait @mutex.synchronize do if @count < @count_max @count += 1 @lock.wait(@mutex) else @count = 1 @lock.broadcast end end nil end |