8000 Better support for `Fiber.set_scheduler`. (#194) · socketry/async@8919adf · GitHub
[go: up one dir, main page]

Skip to content

Commit 8919adf

Browse files
authored
Better support for Fiber.set_scheduler. (#194)
1 parent 070ae5e commit 8919adf

File tree

5 files changed

+42
-0
lines changed

5 files changed

+42
-0
lines changed

lib/async/reactor.rb

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,10 @@ def initialize(...)
2121
Fiber.set_scheduler(self)
2222
end
2323

24+
def scheduler_close
25+
self.close
26+
end
27+
2428
public :sleep
2529
end
2630
end

lib/async/scheduler.rb

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,12 @@ def initialize(parent = nil, selector: nil)
3434
@timers = ::Timers::Group.new
3535
end
3636

37+
def scheduler_close
38+
self.run
39+
ensure
40+
self.close
41+
end
42+
3743
# @public Since `stable-v1`.
3844
def close
3945
# This is a critical step. Because tasks could be stored as instance variables, and since the reactor is (probably) going out of scope, we need to ensure they are stopped. Otherwise, the tasks will belong to a reactor that will never run again and are not stopped.

lib/kernel/async.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ def Async(...)
2525
if current = ::Async::Task.current?
2626
return current.async(...)
2727
else
28+
# This calls Fiber.set_scheduler(self):
2829
reactor = ::Async::Reactor.new
2930

3031
begin

lib/kernel/sync.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ def Sync(&block)
1919
if task = ::Async::Task.current?
2020
yield task
2121
else
22+
# This calls Fiber.set_scheduler(self):
2223
reactor = Async::Reactor.new
2324

2425
begin

test/fiber.rb

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# frozen_string_literal: true
2+
3+
# Released under the MIT License.
4+
# Copyright, 2022, by Samuel Williams.
5+
6+
require 'async/reactor'
7+
8+
describe Fiber do
9+
with '.schedule' do
10+
it "can create several tasks" do
11+
sequence = []
12+
13+
Thread.new do
14+
scheduler = Async::Scheduler.new
15+
Fiber.set_scheduler(scheduler)
16+
17+
Fiber.schedule do
18+
3.times do |i|
19+
Fiber.schedule do
20+
sleep (i / 1000.0)
21+
sequence << i
22+
end
23+
end
24+
end
25+
end.join
26+
27+
expect(sequence).to be == [0, 1, 2]
28+
end
29+
end
30+
end

0 commit comments

Comments
 (0)
0