Class: Bunny::Concurrent::Condition
- Inherits:
-
Object
- Object
- Bunny::Concurrent::Condition
- Defined in:
- lib/bunny/concurrent/condition.rb
Overview
Akin to java.util.concurrent.Condition and intrinsic object monitors (Object#wait, Object#notify, Object#notifyAll) in Java: threads can wait (block until notified) on a condition other threads notify them about. Unlike the j.u.c. version, this one has a single waiting set.
Conditions can optionally be annotated with a description string for ease of debugging.
Instance Attribute Summary collapse
-
#description ⇒ Object
readonly
Returns the value of attribute description.
-
#waiting_threads ⇒ Object
readonly
Returns the value of attribute waiting_threads.
Instance Method Summary collapse
- #any_threads_waiting? ⇒ Boolean
-
#initialize(description = nil) ⇒ Condition
constructor
A new instance of Condition.
- #none_threads_waiting? ⇒ Boolean
- #notify ⇒ Object
- #notify_all ⇒ Object
- #wait ⇒ Object
- #waiting_set_size ⇒ Object
Constructor Details
#initialize(description = nil) ⇒ Condition
Returns a new instance of Condition.
17 18 19 20 21 |
# File 'lib/bunny/concurrent/condition.rb', line 17 def initialize(description = nil) @mutex = Monitor.new @waiting_threads = [] @description = description end |
Instance Attribute Details
#description ⇒ Object (readonly)
Returns the value of attribute description.
14 15 16 |
# File 'lib/bunny/concurrent/condition.rb', line 14 def description @description end |
#waiting_threads ⇒ Object (readonly)
Returns the value of attribute waiting_threads.
14 15 16 |
# File 'lib/bunny/concurrent/condition.rb', line 14 def waiting_threads @waiting_threads end |
Instance Method Details
#any_threads_waiting? ⇒ Boolean
57 58 59 |
# File 'lib/bunny/concurrent/condition.rb', line 57 def any_threads_waiting? @mutex.synchronize { !@waiting_threads.empty? } end |
#none_threads_waiting? ⇒ Boolean
61 62 63 |
# File 'lib/bunny/concurrent/condition.rb', line 61 def none_threads_waiting? @mutex.synchronize { @waiting_threads.empty? } end |
#notify ⇒ Object
32 33 34 35 36 37 38 39 40 41 |
# File 'lib/bunny/concurrent/condition.rb', line 32 def notify @mutex.synchronize do t = @waiting_threads.shift begin t.run if t rescue ThreadError retry end end end |
#notify_all ⇒ Object
43 44 45 46 47 48 49 50 51 |
# File 'lib/bunny/concurrent/condition.rb', line 43 def notify_all @mutex.synchronize do @waiting_threads.each do |t| t.run end @waiting_threads.clear end end |
#wait ⇒ Object
23 24 25 26 27 28 29 30 |
# File 'lib/bunny/concurrent/condition.rb', line 23 def wait @mutex.synchronize do t = Thread.current @waiting_threads.push(t) end Thread.stop end |
#waiting_set_size ⇒ Object
53 54 55 |
# File 'lib/bunny/concurrent/condition.rb', line 53 def waiting_set_size @mutex.synchronize { @waiting_threads.size } end |