Class: VCAP::Services::Base::Barrier

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

Instance Method Summary collapse

Constructor Details

#initialize(options = {}, &callback) ⇒ Barrier

Returns a new instance of Barrier.

Raises:

  • (ArgumentError)


14
15
16
17
18
19
20
21
22
23
# File 'lib/base/barrier.rb', line 14

def initialize(options = {}, &callback)
  raise ArgumentError unless options[:timeout] || options[:callbacks]
  @lock = Mutex.new
  @callback = callback
  @expected_callbacks = options[:callbacks]
  @timer = EM.add_timer(options[:timeout]) {on_timeout} if options[:timeout]
  @callback_fired = false
  @responses = []
  @barrier_callback = Proc.new {|*args| call(*args)}
end

Instance Method Details

#call(*args) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/base/barrier.rb', line 34

def call(*args)
  @lock.synchronize do
    unless @callback_fired
      @responses << args
      if @expected_callbacks
        @expected_callbacks -= 1
        if @expected_callbacks <= 0
          EM.cancel_timer(@timer) if @timer
          @callback_fired = true
          @callback.call(@responses)
        end
      end
    end
  end
end

#callbackObject



50
51
52
# File 'lib/base/barrier.rb', line 50

def callback
  @barrier_callback
end

#on_timeoutObject



25
26
27
28
29
30
31
32
# File 'lib/base/barrier.rb', line 25

def on_timeout
  @lock.synchronize do
    unless @callback_fired
      @callback_fired = true
      @callback.call(@responses)
    end
  end
end