Skip to content
Dhrubomoy Das Gupta edited this page Sep 9, 2016 · 15 revisions

To use Celluloid, define a normal Ruby class that includes Celluloid:

class Sheen
  include Celluloid

  def initialize(name)
    @name = name
  end

  def set_status(status)
    @status = status
  end

  def report
    "#{@name} is #{@status}"
  end
end

Now when you create new instances of this class, they're actually concurrent objects, each running in their own thread, called "cells" (or actors):

>> charlie = Sheen.new "Charlie Sheen"
 => #<Celluloid::Proxy::Cell(Sheen:0xb89764) @name="Charlie Sheen">
>> charlie.set_status "winning!"
 => "winning!"
>> charlie.report
 => "Charlie Sheen is winning!"
>> charlie.async.set_status "asynchronously winning!"
 => #<Celluloid::Proxy::Async(Sheen)>
>> charlie.report
 => "Charlie Sheen is asynchronously winning!"

You can call methods on this concurrent object just like you would any other Ruby object. The Sheen#set_status method works exactly like you'd expect, returning the last expression evaluated.

By calling charlie.async, this instructs Celluloid that you would like for the given method to be called asynchronously. This means that rather than the caller waiting for a response, the caller sends a message to the concurrent object that you'd like the given method invoked, and then the caller proceeds without waiting for a response. The concurrent object receiving the message will then process the method call in the background.

Asynchronous calls will never raise an exception, even if an exception occurs when the receiver is processing it. Worse, unhandled exceptions will crash the receiver, and making an asynchronous call to a crashed object will not raise an error.

However, you can still handle errors created by asynchronous calls using two features of Celluloid called supervisors and linking. See the corresponding sections below for more information.

See also:

  • Actor Lifecycle: cells aren't automatically garbage collected like objects!
  • Futures: call a method asynchronously, but obtain the return value later
  • Celluloid (Module): YARD documentation for the Celluloid module, the primary API for all things Celluloid
Clone this wiki locally