Sha256: a7a920d7308e5a16649387644065c2602fedbf028b96f2fec5531c09934bfb17

Contents?: true

Size: 1.48 KB

Versions: 18

Compression:

Stored size: 1.48 KB

Contents

module BubbleWrap
  module Reactor
    # 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
    class Queue

      # Create a new queue
      def initialize
        @items = []
      end

      # Is the queue empty?
      def empty?
        @items.empty?
      end

      # The size of the queue
      def size
        @items.size
      end

      # Push items onto the work queue. The items will not appear in the queue 
      # immediately, but will be scheduled for addition.
      def push(*items)
        ::BubbleWrap::Reactor.schedule do 
          @items.push(*items)
          @popq.shift.call @items.shift until @items.empty? || @popq.empty?
        end
      end

      # 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.
      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

    end
  end
end

Version data entries

18 entries across 18 versions & 1 rubygems

Version Path
bubble-wrap-1.8.0 motion/reactor/queue.rb
bubble-wrap-1.7.1 motion/reactor/queue.rb
bubble-wrap-1.7.0 motion/reactor/queue.rb
bubble-wrap-1.6.0 motion/reactor/queue.rb
bubble-wrap-1.6.0.rc1 motion/reactor/queue.rb
bubble-wrap-1.5.0 motion/reactor/queue.rb
bubble-wrap-1.5.0.rc1 motion/reactor/queue.rb
bubble-wrap-1.4.0 motion/reactor/queue.rb
bubble-wrap-1.3.0 motion/reactor/queue.rb
bubble-wrap-1.3.0.osx motion/reactor/queue.rb
bubble-wrap-1.2.0 motion/reactor/queue.rb
bubble-wrap-1.2.0.pre motion/reactor/queue.rb
bubble-wrap-1.1.5 motion/reactor/queue.rb
bubble-wrap-1.1.4 motion/reactor/queue.rb
bubble-wrap-1.1.3 motion/reactor/queue.rb
bubble-wrap-1.1.2 motion/reactor/queue.rb
bubble-wrap-1.1.1 motion/reactor/queue.rb
bubble-wrap-1.1.0 motion/reactor/queue.rb