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
if scheduler.is_a?(FiberScheduler)
Fiber.schedule(type, &block)
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 blocking = false
fiber = Fiber.schedule do
FiberScheduler::Compatibility.set_internal!
yield
ensure
finished = true
scheduler.unblock(nil, parent) if blocking
end
if Fiber.blocking?
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
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
|