Class: Pgtk::Pool::IterableQueue
- Inherits:
-
Object
- Object
- Pgtk::Pool::IterableQueue
- Defined in:
- lib/pgtk/pool.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.
Instance Method Summary collapse
- #<<(item) ⇒ Object
-
#initialize(size) ⇒ IterableQueue
constructor
A new instance of IterableQueue.
- #map ⇒ Object
- #pop ⇒ Object
- #size ⇒ Object
Constructor Details
#initialize(size) ⇒ IterableQueue
234 235 236 237 238 239 240 |
# File 'lib/pgtk/pool.rb', line 234 def initialize(size) @size = size @items = [] @taken = [] @mutex = Mutex.new @condition = ConditionVariable.new end |
Instance Method Details
#<<(item) ⇒ Object
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 |
# File 'lib/pgtk/pool.rb', line 242 def <<(item) @mutex.synchronize do if @items.size < @size @items << item @taken << false else index = @items.index(item) if index.nil? index = @taken.index(true) raise 'No taken slot found' if index.nil? @items[index] = item end @taken[index] = false end @condition.signal end end |
#map ⇒ Object
275 276 277 278 279 |
# File 'lib/pgtk/pool.rb', line 275 def map(&) @mutex.synchronize do @items.map(&) end end |
#pop ⇒ Object
260 261 262 263 264 265 266 267 |
# File 'lib/pgtk/pool.rb', line 260 def pop @mutex.synchronize do @condition.wait(@mutex) while @taken.all? || @items.empty? index = @taken.index(false) @taken[index] = true @items[index] end end |
#size ⇒ Object
269 270 271 272 273 |
# File 'lib/pgtk/pool.rb', line 269 def size @mutex.synchronize do @items.size end end |