Class: QueueWithTimeout
- Inherits:
-
Object
- Object
- QueueWithTimeout
- Defined in:
- lib/signalfx/signalflow/queue.rb
Overview
Instance Method Summary collapse
- #<<(x) ⇒ Object
-
#initialize ⇒ QueueWithTimeout
constructor
A new instance of QueueWithTimeout.
- #pop(non_block = false) ⇒ Object
- #pop_with_timeout(timeout = nil) ⇒ Object
Constructor Details
#initialize ⇒ QueueWithTimeout
Returns a new instance of QueueWithTimeout.
7 8 9 10 11 |
# File 'lib/signalfx/signalflow/queue.rb', line 7 def initialize @mutex = Mutex.new @queue = [] @received = ConditionVariable.new end |
Instance Method Details
#<<(x) ⇒ Object
13 14 15 16 17 18 |
# File 'lib/signalfx/signalflow/queue.rb', line 13 def <<(x) @mutex.synchronize do @queue << x @received.signal end end |
#pop(non_block = false) ⇒ Object
20 21 22 |
# File 'lib/signalfx/signalflow/queue.rb', line 20 def pop(non_block = false) pop_with_timeout(non_block ? 0 : nil) end |
#pop_with_timeout(timeout = nil) ⇒ Object
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
# File 'lib/signalfx/signalflow/queue.rb', line 24 def pop_with_timeout(timeout = nil) @mutex.synchronize do if timeout.nil? # wait indefinitely until there is an element in the queue while @queue.empty? @received.wait(@mutex) end elsif @queue.empty? && timeout != 0 # wait for element or timeout timeout_time = timeout + Time.now.to_f while @queue.empty? && (remaining_time = timeout_time - Time.now.to_f) > 0 @received.wait(@mutex, remaining_time) end end #if we're still empty after the timeout, raise exception raise ThreadError, "queue empty" if @queue.empty? @queue.shift end end |