rainbows.git  about / heads / tags
Unicorn for sleepy apps and slow clients
blob e7118f3d618c284abcc11a21f0f6b57e72a0e3c8 956 bytes (raw)
$ git show v0.95.1:lib/rainbows/fiber/queue.rb	# shows this blob on the CLI

 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
 
# -*- encoding: binary -*-
# :enddoc:
module Rainbows
  module Fiber

    # a self-sufficient Queue implementation for Fiber-based concurrency
    # models.  This requires no external scheduler, so it may be used with
    # Revactor as well as FiberSpawn and FiberPool.
    class Queue < Struct.new(:queue, :waiters)

      def initialize(queue = [], waiters = [])
        # move elements of the Queue into an Array
        if queue.class.name == "Queue"
          queue = queue.length.times.map { queue.pop }
        end
        super queue, waiters
      end

      def shift
        # ah the joys of not having to deal with race conditions
        if queue.empty?
          waiters << ::Fiber.current
          ::Fiber.yield
        end
        queue.shift
      end

      def <<(obj)
        queue << obj
        blocked = waiters.shift and blocked.resume
        queue # not quite 100% compatible but no-one's looking :>
      end

    end
  end
end

git clone https://yhbt.net/rainbows.git