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 Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeFuture



24
25
26
27
28
29
30
# File 'lib/celluloid/future.rb', line 24

def initialize
  @address = Celluloid.uuid
  @mutex = Mutex.new
  @ready = false
  @result = nil
  @forwards = nil
end

Instance Attribute Details

#addressObject (readonly)

Returns the value of attribute address



22
23
24
# File 'lib/celluloid/future.rb', line 22

def address
  @address
end

Class Method Details

.new(*args, &block) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/celluloid/future.rb', line 7

def self.new(*args, &block)
  return super unless block

  future = new
  Celluloid::ThreadHandle.new(Celluloid.actor_system, :future) do
    begin
      call = SyncCall.new(future, :call, args)
      call.dispatch(block)
    rescue
      # Exceptions in blocks will get raised when the value is retrieved
    end
  end
  future
end

Instance Method Details

#ready?Boolean

Check if this future has a value yet



33
34
35
# File 'lib/celluloid/future.rb', line 33

def ready?
  @ready
end

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

Signal this future with the given result value



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

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



38
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
# File 'lib/celluloid/future.rb', line 38

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

  begin
    @mutex.lock

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

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

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