espace (owner)

Fork Of

gist: 4631 by tmm1 Poor Man's Fiber (API compa...

Revisions

gist: 8295 Download_button fork
public
Public Clone URL: git://gist.github.com/8295.git
Embed All Files: show embed
fbr.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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# In Ruby 1.9 Fiber.current returns the root fiber if not running within
# the context of a fiber. tmm1's implementation didn't handle that case.
# This gist introduces modifications so that Fiber.current will behave
# as desired.
 
unless defined? Fiber
  require 'thread'
 
  class FiberError < StandardError; end
 
  class Fiber
    def initialize
      raise ArgumentError, 'new Fiber requires a block' unless block_given?
 
      @yield = Queue.new
      @resume = Queue.new
 
      @thread = Thread.new{ @yield.push [ *yield(*@resume.pop) ] }
      @thread.abort_on_exception = true
      @thread[:fiber] = self
    end
    attr_reader :thread
 
    def resume *args
      raise FiberError, 'dead fiber called' unless @thread.alive?
      @resume.push(args)
      result = @yield.pop
      result.size > 1 ? result : result.first
    end
    
    def yield *args
      @yield.push(args)
      result = @resume.pop
      result.size > 1 ? result : result.first
    end
    
    def self.yield *args
      raise FiberError, "can't yield from root fiber" unless fiber = Thread.current[:fiber]
      fiber.yield(*args)
    end
 
    def self.current
      Thread.current[:fiber] or raise FiberError, 'not inside a fiber'
    end
 
    def inspect
      "#<#{self.class}:0x#{self.object_id.to_s(16)}>"
    end
  end
 
  require 'singleton'
  
  class RootFiber < Fiber
    include Singleton
    def initialize
    end
 
    def resume *args
      raise FiberError, "can't resume root fiber"
    end
 
    def yield *args
      raise FiberError, "can't yield from root fiber"
    end
  end
 
  #attach the root fiber to the main thread
  Thread.main[:fiber] = RootFiber.instance
 
end