Actors and Elixir

Elixir runs on the Erlang virtual machine, and Erlang has support for actors built into the language. In fact, the actor model is one of Erlang’s defining characteristics.

And, perhaps surprisingly for something so rich, it’s really simple.

An actor in Elixir is called a process. You create new processes using one of the variants of the spawn function, send messages to it using the <- operator, and receive messages using a receive expression.

Let’s start with spawn:

 process_id = spawn ​fn​ ->
  IO.puts ​"​​In process ​​#{​inspect self()​}​​"
 end
 IO.puts ​"​​Spawned process ​​#{​inspect process_id​}​​"

The spawn function runs the function you pass it as a separate process, returning the process ...

Get Functional Programming: A PragPub Anthology now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.