Class: Celluloid::Future

Inherits:
Object
  • Object
show all
Defined in:
lib/celluloid/future.rb

Overview

Celluloid::Future objects allow methods and blocks to run in the background, their values requested later

Defined Under Namespace

Classes: Result

Instance Method Summary collapse

Constructor Details

#initialize(*args, &block) ⇒ Future

Create a future bound to a given receiver, or with a block to compute



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/celluloid/future.rb', line 8

def initialize(*args, &block)
  @mutex = Mutex.new
  @ready = false
  @result = nil
  @forwards = nil

  if block
    @call = SyncCall.new(self, :call, args)
    InternalPool.get do
      begin
        @call.dispatch(block)
      rescue
        # Exceptions in blocks will get raised when the value is retrieved
      end
    end
  else
    @call = nil
  end
end

Instance Method Details

#execute(receiver, method, args, block) ⇒ Object

Execute the given method in future context



29
30
31
32
33
34
35
36
# File 'lib/celluloid/future.rb', line 29

def execute(receiver, method, args, block)
  @mutex.synchronize do
    raise "already calling" if @call
    @call = SyncCall.new(self, method, args, block)
  end

  receiver << @call
end

#signal(value) ⇒ Object Also known as: <<

Signal this future with the given result value



78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/celluloid/future.rb', line 78

def signal(value)
  result = Result.new(value, self)

  @mutex.synchronize do
    raise "the future has already happened!" if @ready

    if @forwards
      @forwards.is_a?(Array) ? @forwards.each { |f| f << result } : @forwards << result
    end

    @result = result
    @ready = true
  end
end

#value(timeout = nil) ⇒ Object Also known as: call

Obtain the value for this Future



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
71
72
73
74
# File 'lib/celluloid/future.rb', line 39

def value(timeout = nil)
  ready = result = nil

  begin
    @mutex.lock
    raise "no call requested" unless @call

    if @ready
      ready = true
      result = @result
    else
      case @forwards
      when Array
        @forwards << Thread.mailbox
      when NilClass
        @forwards = Thread.mailbox
      else
        @forwards = [@forwards, Thread.mailbox]
      end
    end
  ensure
    @mutex.unlock
  end

  unless ready
    result = Thread.receive(timeout) do |msg|
      msg.is_a?(Future::Result) && msg.future == self
    end
  end

  if result
    result.value
  else
    raise "Timed out"
  end
end