Skip to content

Instantly share code, notes, and snippets.

@notahat
Created November 6, 2009 01:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save notahat/227596 to your computer and use it in GitHub Desktop.
Save notahat/227596 to your computer and use it in GitHub Desktop.
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