Class: Async::Variable

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

Overview

A synchronization primitive that allows one task to wait for another task to resolve a value.

Instance Method Summary collapse

Constructor Details

#initialize(condition = Condition.new) ⇒ Variable

Create a new variable.



14
15
16
17
# File 'lib/async/variable.rb', line 14

def initialize(condition = Condition.new)
  @condition = condition
  @value = nil
end

Instance Method Details

#resolve(value = true) ⇒ Object

Resolve the value.

Signals all waiting tasks.



24
25
26
27
28
29
30
31
32
# File 'lib/async/variable.rb', line 24

def resolve(value = true)
  @value = value
  condition = @condition
  @condition = nil
  
  self.freeze
  
  condition.signal(value)
end

#resolved?Boolean

Whether the value has been resolved.

Returns:

  • (Boolean)


42
43
44
# File 'lib/async/variable.rb', line 42

def resolved?
  @condition.nil?
end

#valueObject

Alias for #wait.



55
56
57
# File 'lib/async/variable.rb', line 55

def value
  self.wait
end

#value=(value) ⇒ Object

Alias for #resolve.



35
36
37
# File 'lib/async/variable.rb', line 35

def value=(value)
  self.resolve(value)
end

#waitObject

Wait for the value to be resolved.



49
50
51
52
# File 'lib/async/variable.rb', line 49

def wait
  @condition&.wait
  return @value
end