Class: Pgtk::Pool::IterableQueue
- Inherits:
-
Object
- Object
- Pgtk::Pool::IterableQueue
- Defined in:
- lib/pgtk/pool/iterable_queue.rb
Overview
Thread-safe queue implementation that supports iteration. Unlike Ruby’s Queue class, this implementation allows safe iteration over all elements while maintaining thread safety for concurrent access.
This class is used internally by Pool to store database connections and provide the ability to iterate over them for inspection purposes.
The queue is bounded by size. When an item is taken out, it remains in the internal array but is marked as “taken”. When returned, it’s placed back in its original slot and marked as available.
- Author
-
Yegor Bugayenko (yegor256@gmail.com)
- Copyright
-
Copyright © 2019-2026 Yegor Bugayenko
- License
-
MIT
Instance Method Summary collapse
-
#initialize(size, timeout) ⇒ IterableQueue
constructor
A new instance of IterableQueue.
- #map ⇒ Object
- #pop ⇒ Object
- #push(item) ⇒ Object
- #size ⇒ Object
Constructor Details
#initialize(size, timeout) ⇒ IterableQueue
Returns a new instance of IterableQueue.
26 27 28 29 30 31 32 33 34 |
# File 'lib/pgtk/pool/iterable_queue.rb', line 26 def initialize(size, timeout) @size = size @timeout = timeout @items = [] @taken = [] @free = [] @mutex = Mutex.new @condition = ConditionVariable.new end |
Instance Method Details
#map ⇒ Object
78 79 80 81 82 |
# File 'lib/pgtk/pool/iterable_queue.rb', line 78 def map(&) @mutex.synchronize do @items.map(&) end end |
#pop ⇒ Object
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
# File 'lib/pgtk/pool/iterable_queue.rb', line 56 def pop @mutex.synchronize do deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + @timeout while @free.empty? remaining = deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC) if remaining <= 0 raise(Pgtk::Pool::Busy, "No free connection appeared in the pool after #{@timeout}s of waiting") end @condition.wait(@mutex, remaining) end index = @free.shift @taken[index] = true @items[index] end end |
#push(item) ⇒ Object
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
# File 'lib/pgtk/pool/iterable_queue.rb', line 36 def push(item) @mutex.synchronize do if @items.size < @size @items << item @taken << false @free << (@items.size - 1) else index = @items.index(item) if index.nil? index = @taken.index(true) raise(StandardError, 'No taken slot found') if index.nil? @items[index] = item end @taken[index] = false @free << index end @condition.signal end end |
#size ⇒ Object
72 73 74 75 76 |
# File 'lib/pgtk/pool/iterable_queue.rb', line 72 def size @mutex.synchronize do @items.size end end |