Class: Variable
- Inherits:
-
Object
- Object
- Variable
- Defined in:
- lib/variable.rb
Overview
Lightweight concurrency variables
These are inspired by Haskells MVar and IVar types.
Defined Under Namespace
Modules: Timer Classes: IVar, MVar, Result
Constant Summary collapse
- EMPTY =
Class.new do const_set(:INSPECT, 'Variable::EMPTY') end.new.freeze
- TIMEOUT =
Class.new do const_set(:INSPECT, 'Variable::TIMEOUT') end.new.freeze
Instance Method Summary collapse
-
#initialize(condition_variable:, mutex:, value: EMPTY) ⇒ undefined
constructor
Initialize object.
-
#read ⇒ Object
Read value, block on empty.
-
#take ⇒ Object
Take value, block on empty.
-
#take_timeout(timeout) ⇒ Result::Timeout, Result::Value
Take value, with timeout.
-
#try_put(value) ⇒ self
Try put value into the variable, non blocking.
-
#with {|Object| ... } ⇒ Object
Execute block with value, blocking.
Constructor Details
#initialize(condition_variable:, mutex:, value: EMPTY) ⇒ undefined
Initialize object
83 84 85 86 87 |
# File 'lib/variable.rb', line 83 def initialize(condition_variable:, mutex:, value: EMPTY) @full = condition_variable.new @mutex = mutex.new @value = value end |
Instance Method Details
#read ⇒ Object
Read value, block on empty
122 123 124 125 126 127 |
# File 'lib/variable.rb', line 122 def read synchronize do wait_full @value end end |
#take ⇒ Object
Take value, block on empty
92 93 94 95 96 97 |
# File 'lib/variable.rb', line 92 def take synchronize do wait_full perform_take end end |
#take_timeout(timeout) ⇒ Result::Timeout, Result::Value
Take value, with timeout
108 109 110 111 112 113 114 115 116 |
# File 'lib/variable.rb', line 108 def take_timeout(timeout) synchronize do if wait_timeout(@full, timeout, &method(:full?)) Result::Timeout.new else Result::Value.new(perform_take) end end end |
#try_put(value) ⇒ self
Try put value into the variable, non blocking
134 135 136 137 138 139 140 |
# File 'lib/variable.rb', line 134 def try_put(value) synchronize do perform_put(value) if empty? end self end |
#with {|Object| ... } ⇒ Object
Execute block with value, blocking
148 149 150 151 152 153 |
# File 'lib/variable.rb', line 148 def with synchronize do wait_full yield @value end end |