Created
January 18, 2009 23:12
-
-
Save tmm1/48802 to your computer and use it in GitHub Desktop.
Continuation based Fiber implementation for Ruby 1.8
This file contains hidden or 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
class Fiber | |
def initialize &blk | |
unless @yield = callcc{|c| c } | |
@ret = blk.call(@ret) | |
@resume.call | |
end | |
end | |
def resume *args | |
if @resume = callcc{|c| c } | |
Thread.current[:fiber] = self | |
@ret = args.size > 1 ? args : args.first | |
@yield.call | |
else | |
@ret | |
end | |
end | |
def yield *args | |
if @yield = callcc{|c| c } | |
@ret = args.size > 1 ? args : args.first | |
@resume.call | |
else | |
@ret | |
end | |
end | |
def self.yield *args | |
Thread.current[:fiber].yield *args | |
end | |
end | |
f = Fiber.new{ |sym| | |
p(sym) | |
puts 'hi' | |
p(Fiber.yield 1) | |
puts 'bye' | |
:end | |
} | |
p(f.resume :begin) | |
p(f.resume 2) | |
__END__ | |
:begin | |
hi | |
1 | |
2 | |
bye | |
:end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment