Module: Kernel

Defined in:
lib/fiber_scheduler.rb

Instance Method Summary collapse

Instance Method Details

#FiberScheduler(type = nil, &block) ⇒ Object



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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/fiber_scheduler.rb', line 13

def FiberScheduler(type = nil, &block)
  if Fiber.scheduler.nil?
    Fiber.set_scheduler(FiberScheduler.new)

    begin
      yield
    ensure
      Fiber.set_scheduler(nil)
    end

  else
    scheduler = Fiber.scheduler
    # Fiber.scheduler already set, just schedule a fiber.
    if scheduler.is_a?(FiberScheduler)
      # The default waiting is 'true' as that is the most intuitive behavior
      # for a nested FiberScheduler call.
      Fiber.schedule(type, &block)

      # Unknown fiber scheduler class; can't just pass options to
      # Fiber.schedule, handle each option separately.
    else
      scheduler.singleton_class.prepend(FiberScheduler::Compatibility)

      case type
      when :blocking
        fiber = Fiber.new(blocking: true) do
          FiberScheduler::Compatibility.set_internal!
          yield
        end
        fiber.tap(&:resume)

      when :waiting
        parent = Fiber.current
        finished = false # prevents races
        blocking = false # prevents #unblock-ing a fiber that never blocked

        fiber = Fiber.schedule do
          FiberScheduler::Compatibility.set_internal!
          yield
        ensure
          finished = true
          scheduler.unblock(nil, parent) if blocking
        end

        if Fiber.blocking?
          # In a blocking fiber, which is potentially also a loop fiber so
          # there's nothing we can transfer to. Run other fibers (or just
          # block) until waiting fiber finishes.
          until finished
            scheduler.run_once
          end
        elsif !finished
          blocking = true
          scheduler.block(nil, nil)
        end

        fiber

      when :volatile
        scheduler.unblock(nil, Fiber.current)

        fiber = Fiber.new(blocking: false) do
          FiberScheduler::Compatibility.set_internal!
          yield
        rescue FiberScheduler::Compatibility::Close
          # Fiber scheduler is closing.
        ensure
          scheduler._volatile.delete(Fiber.current)
        end
        scheduler._volatile[fiber] = nil
        fiber.tap(&:transfer)

      when nil
        Fiber.schedule do
          FiberScheduler::Compatibility.set_internal!
          yield
        end

      else
        raise "Unknown type"
      end
    end
  end
end