Sha256: 413fb87ba8e9f6561dcf5cecd094a4d8d20bb3e4c538002e85d4e1888d96a7fd

Contents?: true

Size: 1.04 KB

Versions: 10

Compression:

Stored size: 1.04 KB

Contents

module LightIO::Core
  # Provide a safe way to transfer beam/fiber control flow.
  #
  # @Example:
  #   future = Future.new
  #   # future#value will block current beam
  #   Beam.new{future.value}
  #   # use transfer to set value
  #   future.transfer(1)
  class Future
    def initialize
      @value = nil
      @ioloop = IOloop.current
      @state = :init
    end

    def done?
      @state == :done
    end

    # Transfer and set result value
    #
    # use this method to set back result
    def transfer(value=nil)
      raise LightIO::Error, "state error" if done?
      @value = value
      done!
      @light_fiber.transfer if @light_fiber
    end

    def value=(value)
      transfer(value)
    end

    # Get value
    #
    # this method will block current beam/fiber, until future result is set.
    def value
      return @value if done?
      raise LightIO::Error, 'already used' if @light_fiber
      @light_fiber = LightFiber.current
      @ioloop.transfer
      @value
    end

    private

    def done!
      @state = :done
    end
  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
lightio-0.4.2 lib/lightio/core/future.rb
lightio-0.4.1 lib/lightio/core/future.rb
lightio-0.4.0 lib/lightio/core/future.rb
lightio-0.4.0.pre lib/lightio/core/future.rb
lightio-0.3.2 lib/lightio/core/future.rb
lightio-0.3.1 lib/lightio/core/future.rb
lightio-0.3.0 lib/lightio/core/future.rb
lightio-0.2.2 lib/lightio/core/future.rb
lightio-0.2.1 lib/lightio/core/future.rb
lightio-0.2.0 lib/lightio/core/future.rb