Skip to content

Instantly share code, notes, and snippets.

@tmm1
Created January 18, 2009 23:12
Show Gist options
  • Save tmm1/48802 to your computer and use it in GitHub Desktop.
Save tmm1/48802 to your computer and use it in GitHub Desktop.
Continuation based Fiber implementation for Ruby 1.8
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