Class: Datadog::Core::Remote::Component::Barrier

Inherits:
Object
  • Object
show all
Defined in:
lib/datadog/core/remote/component.rb

Overview

Barrier provides a mechanism to fence execution until a condition happens

Instance Method Summary collapse

Constructor Details

#initialize(timeout = nil) ⇒ Barrier

Returns a new instance of Barrier.



94
95
96
97
98
99
100
# File 'lib/datadog/core/remote/component.rb', line 94

def initialize(timeout = nil)
  @once = false
  @timeout = timeout

  @mutex = Mutex.new
  @condition = ConditionVariable.new
end

Instance Method Details

#liftObject

Release all current waiters



138
139
140
141
142
143
144
145
146
# File 'lib/datadog/core/remote/component.rb', line 138

def lift
  @mutex.lock

  @once ||= true

  @condition.broadcast
ensure
  @mutex.unlock
end

#wait_once(timeout = nil) ⇒ Object

Wait for first lift to happen, otherwise don’t wait



103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
# File 'lib/datadog/core/remote/component.rb', line 103

def wait_once(timeout = nil)
  # TTAS (Test and Test-And-Set) optimisation
  # Since @once only ever goes from false to true, this is semantically valid
  return :pass if @once

  begin
    @mutex.lock

    return :pass if @once

    timeout ||= @timeout

    # - starting with Ruby 3.2, ConditionVariable#wait returns nil on
    #   timeout and an integer otherwise
    # - before Ruby 3.2, ConditionVariable returns itself
    # so we have to rely on @once having been set
    if RUBY_VERSION >= '3.2'
      lifted = @condition.wait(@mutex, timeout)
    else
      @condition.wait(@mutex, timeout)
      lifted = @once
    end

    if lifted
      :lift
    else
      @once = true
      :timeout
    end
  ensure
    @mutex.unlock
  end
end