Created
November 6, 2009 01:28
-
-
Save notahat/227596 to your computer and use it in GitHub Desktop.
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
if RUBY_VERSION.starts_with?("1.8") | |
# This is a partial implementation of Fibers for Ruby 1.8 (they're normally | |
# a 1.9 only feature.) | |
# | |
# It does just enough to let me use it for testing some communications code. | |
# In particular, you can only have one Fiber alive at any given time! | |
# | |
# It uses continuations, so is probably pretty slow and memory hungry. | |
class Fiber | |
cattr_accessor :instance | |
def initialize(&block) | |
Fiber.instance = self | |
@block = block | |
end | |
def resume(value = nil) | |
raise "Resume on a completed fiber" if @finished | |
callcc do |@outside| | |
result = (@inside || @block).call(value) | |
@finished = true | |
@outside.call(result) | |
end | |
end | |
def yield(value = nil) | |
callcc {|@inside| @outside.call(value) } | |
end | |
def self.yield(value = nil) | |
Fiber.instance.yield(value) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment