Sha256: 490758e2dff4d7441140428f30c913a55a3307776f8a0a3e19a91984b8f6e680

Contents?: true

Size: 832 Bytes

Versions: 9

Compression:

Stored size: 832 Bytes

Contents

require 'em-synchrony'

module Kernel
  def go(*args, &blk)
    EM.next_tick do
      Fiber.new { blk.call(*args) }.resume
    end
  end
end

class Channel < EM::Queue
  def initialize(opts = {})
    @limit = opts[:size]
    @prodq = []
    @size  = 0

    super()
  end

  def size; @size; end
  def empty?; size == 0; end

  def pop
    f = Fiber.current
    clb = Proc.new do |*args|
      @size -= 1
      f.resume(args)
      @prodq.shift.call if !@prodq.empty?
    end

    super(&clb)
    Fiber.yield
  end

  def push(*items)
    f = Fiber.current
    @size += 1

    EM.next_tick { super(*items) }

    # if the queue is bounded, then suspend the producer
    # until someone consumes a pending message
    if @limit && size >= @limit
      @prodq.push -> { f.resume }
      Fiber.yield
    end
  end
  alias :<< :push
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
em-synchrony-1.0.6 examples/go/go.rb
em-synchrony-1.0.5 examples/go/go.rb
em-synchrony-1.0.4 examples/go/go.rb
em-synchrony-1.0.3 examples/go/go.rb
em-synchrony-1.0.2 examples/go/go.rb
em-synchrony-1.0.1 examples/go/go.rb
em-synchrony-1.0.0 examples/go/go.rb
em-synchrony-0.3.0.beta.1 examples/go/go.rb
em-synchrony-0.2.0 examples/go/go.rb