Class: CopyTunerClient::QueueWithTimeout
- Inherits:
-
Object
- Object
- CopyTunerClient::QueueWithTimeout
- Defined in:
- lib/copy_tuner_client/queue_with_timeout.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
- #uniq_push(x) ⇒ Object
Constructor Details
#initialize ⇒ QueueWithTimeout
Returns a new instance of QueueWithTimeout.
4 5 6 7 8 |
# File 'lib/copy_tuner_client/queue_with_timeout.rb', line 4 def initialize @mutex = Mutex.new @queue = [] @received = ConditionVariable.new end |
Instance Method Details
#<<(x) ⇒ Object
10 11 12 13 14 15 |
# File 'lib/copy_tuner_client/queue_with_timeout.rb', line 10 def <<(x) @mutex.synchronize do @queue << x @received.signal end end |
#pop(non_block = false) ⇒ Object
26 27 28 |
# File 'lib/copy_tuner_client/queue_with_timeout.rb', line 26 def pop(non_block = false) pop_with_timeout(non_block ? 0 : nil) end |
#pop_with_timeout(timeout = nil) ⇒ Object
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
# File 'lib/copy_tuner_client/queue_with_timeout.rb', line 30 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 |
#uniq_push(x) ⇒ Object
17 18 19 20 21 22 23 24 |
# File 'lib/copy_tuner_client/queue_with_timeout.rb', line 17 def uniq_push(x) @mutex.synchronize do unless @queue.member?(x) @queue << x @received.signal end end end |