Skip to content

Better support for Fiber.set_scheduler. #194

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 2, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions lib/async/reactor.rb
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ def initialize(...)
Fiber.set_scheduler(self)
end

def scheduler_close
self.close
end

public :sleep
end
end
6 changes: 6 additions & 0 deletions lib/async/scheduler.rb
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,12 @@ def initialize(parent = nil, selector: nil)
@timers = ::Timers::Group.new
end

def scheduler_close
self.run
ensure
self.close
end

# @public Since `stable-v1`.
def close
# 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.
Expand Down
1 change: 1 addition & 0 deletions lib/kernel/async.rb
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ def Async(...)
if current = ::Async::Task.current?
return current.async(...)
else
# This calls Fiber.set_scheduler(self):
reactor = ::Async::Reactor.new

begin
Expand Down
1 change: 1 addition & 0 deletions lib/kernel/sync.rb
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ def Sync(&block)
if task = ::Async::Task.current?
yield task
else
# This calls Fiber.set_scheduler(self):
reactor = Async::Reactor.new

begin
Expand Down
30 changes: 30 additions & 0 deletions test/fiber.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# frozen_string_literal: true

# Released under the MIT License.
# Copyright, 2022, by Samuel Williams.

require 'async/reactor'

describe Fiber do
with '.schedule' do
it "can create several tasks" do
sequence = []

Thread.new do
scheduler = Async::Scheduler.new
Fiber.set_scheduler(scheduler)

Fiber.schedule do
3.times do |i|
Fiber.schedule do
sleep (i / 1000.0)
sequence << i
end
end
end
end.join

expect(sequence).to be == [0, 1, 2]
end
end
end