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.
19 20 21 22 23 |
# File 'lib/bunny/concurrent/condition.rb', line 19 def initialize(description = nil) @mutex = Monitor.new @waiting_threads = [] @description = description end |
Instance Attribute Details
#description ⇒ Object (readonly)
Returns the value of attribute description.
16 17 18 |
# File 'lib/bunny/concurrent/condition.rb', line 16 def description @description end |
#waiting_threads ⇒ Object (readonly)
Returns the value of attribute waiting_threads.
16 17 18 |
# File 'lib/bunny/concurrent/condition.rb', line 16 def waiting_threads @waiting_threads end |
Instance Method Details
#any_threads_waiting? ⇒ Boolean
59 60 61 |
# File 'lib/bunny/concurrent/condition.rb', line 59 def any_threads_waiting? @mutex.synchronize { !@waiting_threads.empty? } end |
#none_threads_waiting? ⇒ Boolean
63 64 65 |
# File 'lib/bunny/concurrent/condition.rb', line 63 def none_threads_waiting? @mutex.synchronize { @waiting_threads.empty? } end |
#notify ⇒ Object
34 35 36 37 38 39 40 41 42 43 |
# File 'lib/bunny/concurrent/condition.rb', line 34 def notify @mutex.synchronize do t = @waiting_threads.shift begin t.run if t rescue ThreadError retry end end end |
#notify_all ⇒ Object
45 46 47 48 49 50 51 52 53 |
# File 'lib/bunny/concurrent/condition.rb', line 45 def notify_all @mutex.synchronize do @waiting_threads.each do |t| t.run end @waiting_threads.clear end end |
#wait ⇒ Object
25 26 27 28 29 30 31 32 |
# File 'lib/bunny/concurrent/condition.rb', line 25 def wait @mutex.synchronize do t = Thread.current @waiting_threads.push(t) end Thread.stop end |
#waiting_set_size ⇒ Object
55 56 57 |
# File 'lib/bunny/concurrent/condition.rb', line 55 def waiting_set_size @mutex.synchronize { @waiting_threads.size } end |