Class: BubbleWrap::Reactor::Queue
- Inherits:
-
Object
- Object
- BubbleWrap::Reactor::Queue
- Defined in:
- motion/reactor/queue.rb
Overview
A GCD scheduled, linear queue.
This class provides a simple “Queue” like abstraction on top of the GCD scheduler.
Useful as an API sugar for stateful protocols
q = BubbleWrap::Reactor::Queue.new
q.push('one', 'two', 'three')
3.times do
q.pop{ |msg| puts(msg) }
end
Instance Method Summary collapse
-
#empty? ⇒ Boolean
Is the queue empty?.
-
#initialize ⇒ Queue
constructor
Create a new queue.
-
#pop(*args, &blk) ⇒ Object
Pop items off the queue, running the block on the work queue.
-
#push(*items) ⇒ Object
Push items onto the work queue.
-
#size ⇒ Object
The size of the queue.
Constructor Details
#initialize ⇒ Queue
Create a new queue
18 19 20 |
# File 'motion/reactor/queue.rb', line 18 def initialize @items = [] end |
Instance Method Details
#empty? ⇒ Boolean
Is the queue empty?
23 24 25 |
# File 'motion/reactor/queue.rb', line 23 def empty? @items.empty? end |
#pop(*args, &blk) ⇒ Object
Pop items off the queue, running the block on the work queue. The pop will not happen immediately, but at some point in the future, either in the next tick, if the queue has data, or when the queue is populated.
44 45 46 47 48 49 50 51 52 53 54 55 56 |
# File 'motion/reactor/queue.rb', line 44 def pop(*args, &blk) cb = proc do blk.call(*args) end ::BubbleWrap::Reactor.schedule do if @items.empty? @popq << cb else cb.call @items.shift end end nil # Always returns nil end |
#push(*items) ⇒ Object
Push items onto the work queue. The items will not appear in the queue immediately, but will be scheduled for addition.
34 35 36 37 38 39 |
# File 'motion/reactor/queue.rb', line 34 def push(*items) ::BubbleWrap::Reactor.schedule do @items.push(*items) @popq.shift.call @items.shift until @items.empty? || @popq.empty? end end |
#size ⇒ Object
The size of the queue
28 29 30 |
# File 'motion/reactor/queue.rb', line 28 def size @items.size end |