File: go.rb

package info (click to toggle)
ruby-em-synchrony 1.0.5-3.1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye
  • size: 572 kB
  • sloc: ruby: 3,458; sh: 37; sql: 7; makefile: 2
file content (49 lines) | stat: -rw-r--r-- 832 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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