Sha256: e9d129fe1377e3b48aee65502a63bf8cadcfda6b21770051abab13cb5fd8ab62

Contents?: true

Size: 1.29 KB

Versions: 1

Compression:

Stored size: 1.29 KB

Contents

require 'thread'

module Celluloid
  # Celluloid::Future objects allow methods and blocks to run in the
  # background, their values requested later
  class Future
    # Create a new Celluloid::Future object, allowing a block to be computed in
    # the background and its return value obtained later
    def initialize(*args, &block)
      @lock = Mutex.new
      @value_obtained = false

      @runner = Runner.new(*args, &block)
      @runner.run!
    end

    # Obtain the value for this Future
    def value
      @lock.synchronize do
        unless @value_obtained
          @value = @runner.value
          @runner.terminate
          @value_obtained = true
        end

        @value
      end
    end
    alias_method :call, :value

    # Inspect this Celluloid::Future
    alias_method :inspect, :to_s

    # Runner is an internal class which executes the given block/method
    class Runner
      include Celluloid

      def initialize(*args, &block)
        @args, @block = args, block
      end

      def run
        @value = @block.call(*@args)
      rescue Exception => error
        @error = error
      ensure
        @called = true
        signal :finished
      end

      def value
        wait :finished unless @called
        abort @error if @error
        @value
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
celluloid-0.7.0 lib/celluloid/future.rb