Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
All of reactor spec passing using
Fiber#transfer
only.
- Loading branch information
Showing
4 changed files
with
99 additions
and
17 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,64 @@ | ||
#!/usr/bin/env ruby | ||
|
||
require 'fiber' | ||
|
||
module Async | ||
class Reactor | ||
def initialize | ||
@fiber = nil | ||
@waiting = [] | ||
end | ||
|
||
def yield | ||
@fiber.transfer | ||
end | ||
|
||
def resume(fiber) | ||
previous = @fiber | ||
|
||
@fiber = Fiber.current | ||
fiber.transfer | ||
|
||
@fiber = previous | ||
end | ||
|
||
def async(&block) | ||
fiber = Fiber.new do | ||
block.call | ||
self.yield | ||
end | ||
|
||
resume(fiber) | ||
end | ||
|
||
# Wait for some event... | ||
def wait | ||
@waiting << Fiber.current | ||
self.yield | ||
end | ||
|
||
def run | ||
while @waiting.any? | ||
fiber = @waiting.pop | ||
resume(fiber) | ||
end | ||
end | ||
end | ||
end | ||
|
||
reactor = Async::Reactor.new | ||
|
||
reactor.async do | ||
puts "Hello World" | ||
reactor.async do | ||
puts "Goodbye World" | ||
reactor.wait | ||
puts "I'm back!" | ||
end | ||
puts "Foo Bar" | ||
end | ||
|
||
puts "Running" | ||
reactor.run | ||
puts "Finished" | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters