Sha256: fb55c3ce397179a08750d5f89b0a887226017abf7802e6b6d5fda8db59aea0ce

Contents?: true

Size: 1.16 KB

Versions: 30

Compression:

Stored size: 1.16 KB

Contents

# Poor Man's Fiber (API compatible Thread based Fiber implementation for Ruby 1.8)
# (c) 2008 Aman Gupta (tmm1)

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
end

Version data entries

30 entries across 30 versions & 5 rubygems

Version Path
riak-client-0.8.2 lib/riak/util/fiber1.8.rb
riak-client-0.8.1 lib/riak/util/fiber1.8.rb
riak-client-0.8.0 lib/riak/util/fiber1.8.rb
riak-client-0.8.0.beta2 lib/riak/util/fiber1.8.rb
riak-client-0.8.0.beta lib/riak/util/fiber1.8.rb
riak-client-0.7.1 lib/riak/util/fiber1.8.rb
riak-client-0.7.0 lib/riak/util/fiber1.8.rb
ripple-0.6.1 lib/riak/util/fiber1.8.rb
ripple-0.6.0 lib/riak/util/fiber1.8.rb
darkext-0.12.0 lib/darkext/fiber.rb