Sha256: 9e612e98d5101af1e2f1c245105b9027ca874c2dab482f64d318908a91edcf4e

Contents?: true

Size: 1.2 KB

Versions: 42

Compression:

Stored size: 1.2 KB

Contents

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(*wait)] }
      @thread.abort_on_exception = true
      @thread[:fiber] = self
    end
    attr_reader :yield, :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 wait
      @resume.pop
    end
    
    def self.yield *args
      raise FiberError, "can't yield from root fiber" unless fiber = Thread.current[:fiber]
      fiber.yield.push(args)
      result = fiber.wait
      result.size > 1 ? result : result.first
    end

    def inspect
      "#<#{self.class}:0x#{self.object_id.to_s(16)}>"
    end
  end
end

if __FILE__ == $0
  f = Fiber.new{ puts 'hi'; p Fiber.yield(1); puts 'bye'; :done }
  p f.resume
  p f.resume(2)
end

__END__

$ ruby fbr.rb 
hi
1
2
bye
:done

$ ruby1.9 fbr.rb 
hi
1
2
bye
:done

Version data entries

42 entries across 42 versions & 5 rubygems

Version Path
Pistos-ramaze-2008.09 lib/ramaze/snippets/fiber.rb
Pistos-ramaze-2008.12 lib/ramaze/snippets/fiber.rb
Pistos-ramaze-2009.01 lib/ramaze/snippets/fiber.rb
Pistos-ramaze-2009.02 lib/ramaze/snippets/fiber.rb
Pistos-ramaze-2009.04.08 lib/ramaze/snippets/fiber.rb
Pistos-ramaze-2009.06.12 lib/ramaze/snippets/fiber.rb
manveru-ramaze-2008.08 lib/ramaze/snippets/fiber.rb
manveru-ramaze-2008.09 lib/ramaze/snippets/fiber.rb
manveru-ramaze-2008.10 lib/ramaze/snippets/fiber.rb
manveru-ramaze-2008.12 lib/ramaze/snippets/fiber.rb
manveru-ramaze-2009.01 lib/ramaze/snippets/fiber.rb
manveru-ramaze-2009.04.01 lib/ramaze/snippets/fiber.rb
manveru-ramaze-2009.04.08 lib/ramaze/snippets/fiber.rb
manveru-ramaze-2009.04.18 lib/ramaze/snippets/fiber.rb
manveru-ramaze-2009.04.22 lib/ramaze/snippets/fiber.rb
manveru-ramaze-2009.04 lib/ramaze/snippets/fiber.rb
manveru-ramaze-2009.05.08 lib/ramaze/snippets/fiber.rb
manveru-ramaze-2009.05 lib/ramaze/snippets/fiber.rb
manveru-ramaze-2009.06.04 lib/ramaze/snippets/fiber.rb
manveru-ramaze-2009.06.12 lib/ramaze/snippets/fiber.rb