Class: Celluloid::Task

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

Overview

Tasks are interruptable/resumable execution contexts used to run methods

Defined Under Namespace

Classes: TerminatedError

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(type) ⇒ Task

Run the given block within a task



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/celluloid/task.rb', line 30

def initialize(type)
  @type   = type
  @status = :new

  actor   = Thread.current[:actor]
  mailbox = Thread.current[:mailbox]

  @fiber = Fiber.new do
    @status = :running
    Thread.current[:actor]   = actor
    Thread.current[:mailbox] = mailbox
    Fiber.current.task = self
    actor.tasks << self

    begin
      yield
    rescue TerminatedError
      # Task was explicitly terminated
    ensure
      actor.tasks.delete self
    end
  end
end

Instance Attribute Details

#statusObject

Returns the value of attribute status.



10
11
12
# File 'lib/celluloid/task.rb', line 10

def status
  @status
end

#typeObject (readonly)

Returns the value of attribute type.



9
10
11
# File 'lib/celluloid/task.rb', line 9

def type
  @type
end

Class Method Details

.currentObject

Obtain the current task



13
14
15
# File 'lib/celluloid/task.rb', line 13

def self.current
  Fiber.current.task or raise "no task for this Fiber"
end

.suspend(status) ⇒ Object

Suspend the running task, deferring to the scheduler

Raises:



18
19
20
21
22
23
24
25
26
27
# File 'lib/celluloid/task.rb', line 18

def self.suspend(status)
  task = Task.current
  task.status = status

  result = Fiber.yield
  raise TerminatedError, "task was terminated" if result == TerminatedError
  task.status = :running

  result
end

Instance Method Details

#inspectObject

Nicer string inspect for tasks



77
78
79
# File 'lib/celluloid/task.rb', line 77

def inspect
  "<Celluloid::Task:0x#{object_id.to_s(16)} @type=#{@type.inspect}, @status=#{@status.inspect}, @running=#{@fiber.alive?}>"
end

#resume(value = nil) ⇒ Object

Resume a suspended task, giving it a value to return if needed



55
56
57
58
59
60
61
62
63
64
# File 'lib/celluloid/task.rb', line 55

def resume(value = nil)
  @fiber.resume value
  nil
rescue FiberError
  raise DeadTaskError, "cannot resume a dead task"
rescue RuntimeError => ex
  # These occur spuriously on 1.9.3 if we shut down an actor with running tasks
  return if ex.message == ""
  raise
end

#running?Boolean

Is the current task still running?

Returns:

  • (Boolean)


74
# File 'lib/celluloid/task.rb', line 74

def running?; @fiber.alive?; end

#terminateObject

Terminate this task



67
68
69
70
71
# File 'lib/celluloid/task.rb', line 67

def terminate
  resume TerminatedError if @fiber.alive?
rescue FiberError
  # If we're getting this the task should already be dead
end