Class: Datadog::Core::Remote::Component::Barrier
- Inherits:
-
Object
- Object
- Datadog::Core::Remote::Component::Barrier
- Defined in:
- lib/datadog/core/remote/component.rb
Overview
Barrier provides a mechanism to fence execution until a condition happens
Instance Method Summary collapse
-
#initialize(timeout = nil) ⇒ Barrier
constructor
A new instance of Barrier.
-
#lift ⇒ Object
Release all current waiters.
-
#wait_once(timeout = nil) ⇒ Object
Wait for first lift to happen, otherwise don’t wait.
Constructor Details
#initialize(timeout = nil) ⇒ Barrier
Returns a new instance of Barrier.
93 94 95 96 97 98 99 |
# File 'lib/datadog/core/remote/component.rb', line 93 def initialize(timeout = nil) @once = false @timeout = timeout @mutex = Mutex.new @condition = ConditionVariable.new end |
Instance Method Details
#lift ⇒ Object
Release all current waiters
137 138 139 140 141 142 143 144 145 |
# File 'lib/datadog/core/remote/component.rb', line 137 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
102 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 |
# File 'lib/datadog/core/remote/component.rb', line 102 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 |