notahat (owner)

Revisions

gist: 227596 Download_button fork
public
Public Clone URL: git://gist.github.com/227596.git
Embed All Files: show embed
fibers_hack.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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