Class: OsCtl::Lib::Queue
- Inherits:
-
Object
- Object
- OsCtl::Lib::Queue
- Defined in:
- lib/libosctl/queue.rb
Overview
Replacement for stock Queue
Instance Method Summary collapse
- #any? ⇒ Boolean
-
#clear ⇒ Object
Clear the queue.
- #empty? ⇒ Boolean
-
#initialize ⇒ Queue
constructor
A new instance of Queue.
-
#insert(v) ⇒ Object
Insert value to the beginning of the queue.
- #length ⇒ Object
-
#push(v) ⇒ Object
(also: #<<)
Add value into queue.
-
#shift(block: true, timeout: nil) ⇒ Object
(also: #pop)
Remove the first element from the queue and return it.
- #sync ⇒ Object protected
-
#to_a ⇒ Array
Return the queued values as an array.
Constructor Details
#initialize ⇒ Queue
Returns a new instance of Queue.
6 7 8 9 10 |
# File 'lib/libosctl/queue.rb', line 6 def initialize @mutex = ::Mutex.new @cond = ConditionVariable.new @queue = [] end |
Instance Method Details
#any? ⇒ Boolean
71 72 73 |
# File 'lib/libosctl/queue.rb', line 71 def any? !empty? end |
#clear ⇒ Object
Clear the queue
61 62 63 |
# File 'lib/libosctl/queue.rb', line 61 def clear sync { @queue.clear } end |
#empty? ⇒ Boolean
66 67 68 |
# File 'lib/libosctl/queue.rb', line 66 def empty? sync { @queue.empty? } end |
#insert(v) ⇒ Object
Insert value to the beginning of the queue
24 25 26 27 28 29 |
# File 'lib/libosctl/queue.rb', line 24 def insert(v) sync do @queue.insert(0, v) @cond.signal end end |
#length ⇒ Object
75 76 77 |
# File 'lib/libosctl/queue.rb', line 75 def length sync { @queue.length } end |
#push(v) ⇒ Object Also known as: <<
Add value into queue
13 14 15 16 17 18 |
# File 'lib/libosctl/queue.rb', line 13 def push(v) sync do @queue << v @cond.signal end end |
#shift(block: true, timeout: nil) ⇒ Object Also known as: pop
Remove the first element from the queue and return it
If `block` is `true`, this method will block until there is something to return. If `block` is `false` and the queue is empty, `nil` is returned. If `timeout` is set and passes, `nil` is returned.
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
# File 'lib/libosctl/queue.rb', line 39 def shift(block: true, timeout: nil) sync do if @queue.any? @queue.shift elsif block # Wait for something to be pushed loop do @cond.wait(@mutex, timeout) break if @queue.any? || timeout end @queue.shift else nil end end end |
#sync ⇒ Object (protected)
86 87 88 |
# File 'lib/libosctl/queue.rb', line 86 def sync @mutex.synchronize { yield } end |
#to_a ⇒ Array
Return the queued values as an array
81 82 83 |
# File 'lib/libosctl/queue.rb', line 81 def to_a sync { @queue.clone } end |