Processes
A process in Elixir is a small unit of work that the Erlang VM schedules itself: it has a pid, a mailbox and its own stack, and it costs a few hundred words of memory. Processes do not share memory; they send messages, and a receive block takes them out of the mailbox. This lesson is the raw API, spawn, send and receive, on which Task, Agent and GenServer are built.
spawn, send and receive
spawn/1 takes a function and starts it in a new process, and answers the pid of that process at once; the function runs beside the caller. send/2 puts a message in a mailbox, and receive takes the first message that matches, waiting until one arrives:
spawn.exs
pid = spawn(fn -> receive do {:ping, from} -> send(from, :pong) end end) send(pid, {:ping, self()}) receive do :pong -> IO.puts("pong received") end
elixir spawn.exs
pong received
The child learns whom to answer from the message itself: the caller put self(), its own pid, in the tuple. That is the convention of every protocol between processes in Elixir, and a reply is a message the same way. The child process ends when its function returns; nothing has to stop it.
The pid that answers
The value self/0 answers is the pid of the process that calls it, and is_pid/1 is the check. A pid is printed with a number and a creation number between the angle brackets, and that text is for a reader rather than for a program:
pid.exs
IO.inspect(is_pid(self())) IO.puts(inspect(self()) |> String.starts_with?("#PID")) pid = spawn(fn -> :ok end) IO.inspect(is_pid(pid))
elixir pid.exs
true
true
true
The exact pid changes on every run and on every machine, so a page cannot show one and a program does not compare one with a literal. A pid is passed in messages, kept in a registry or stored in the state of another process; the lesson on tasks and agents shows the tools that keep them for a program.
A process that keeps a number
A process that loops with an argument is the mutable cell of a functional language: the number lives in the loop, and the messages change it. The module below hides the loop behind three functions, so the caller sends a message and reads an answer:
counter.exs
defmodule Counter do def start do spawn(fn -> loop(0) end) end def increment(pid) do send(pid, :inc) end def value(pid) do send(pid, {:value, self()}) receive do {:value, n} -> n end end defp loop(n) do receive do :inc -> loop(n + 1) {:value, from} -> send(from, {:value, n}) loop(n) end end end pid = Counter.start() Counter.increment(pid) Counter.increment(pid) IO.puts(Counter.value(pid))
elixir counter.exs
2
The two increments are messages that arrive before the question, and the mailbox keeps their order, so the answer is 2. A value call sends the caller pid and waits for the reply, which is a call; an increment sends and does not wait, which is a cast. GenServer is this module with the loop, the naming and the supervision written for you, and the OTP part of the course builds it.
A receive with a timeout
receive waits forever when no message matches, which is wrong for a program that talks to a process that may be gone. The after clause gives the wait a limit in milliseconds, and its body runs when nothing arrived:
timeout.exs
pid = spawn(fn -> :ok end) send(pid, :hello) receive do :hello -> IO.puts("got it") after 100 -> IO.puts("no answer") end
elixir timeout.exs
no answer
The child had already finished when the message was sent, so nothing could answer and the timeout fired after a tenth of a second. A call to another process carries the same limit for the same reason, which is what GenServer.call/3 does with its third argument; a program that waits without one hangs when the other side does not answer.
The mistake: a message to a process that is gone
send/2 succeeds for any pid, dead or alive: the message is accepted and dropped, and the call answers the message itself. Nothing in the program says that the other side never read it:
mistake.exs
pid = spawn(fn -> :ok end) Process.sleep(50) IO.inspect(Process.alive?(pid)) IO.inspect(send(pid, :hello))
elixir mistake.exs
false
:hello
The :hello after the false is the shape of the bug: the send is not an error, and the program goes on as if the work had been done. The tools that answer this are the ones of the OTP part: a supervisor notices that the process is gone and starts a new one, Process.monitor/1 sends a message when it dies, and a call with a timeout fails instead of returning nothing.
The programs on this page were run with Elixir 1.19.7 on Erlang/OTP 27 (erts 15.2.7.14), on Linux x86_64 in a Docker container.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
spawn/1answer?Answer
the pid of the new process, at once
The call starts the function in a new process and returns its pid without waiting for it.
-
How do two processes share data?
Answer
by sending messages
Processes do not share memory; each has a mailbox, and messages are copies.
-
What does a
receiveblock do with a message that does not match its patterns?Answer
it leaves it in the mailbox for a later receive
The mailbox keeps unmatched messages, which is what selective receive means.
-
Why does a call to another process carry a timeout?
Answer
because a process that is gone never answers and the wait would hang
Without a limit a caller waits forever for an answer that cannot come.
-
What does this program print?
pid = spawn(fn -> receive do {:ping, from} -> send(from, :pong) end end) send(pid, {:ping, self()}) receive do :pong -> IO.puts("pong") endAnswer
pong
The child answers the caller pid it was given, and the caller prints the reply.
-
What does this program print?
IO.inspect(is_pid(self()))Answer
true
Every process, the script included, has a pid of its own.
-
What does this program print?
pid = spawn(fn -> :ok end) send(pid, :hello) IO.inspect(send(pid, :again))Answer
:again
send answers the message it was given, whatever the other process does with it.
-
What does this program print?
pid = spawn(fn -> :ok end) send(pid, :hello) receive do :hello -> IO.puts("got it") after 50 -> IO.puts("no answer") endAnswer
no answer
The child has finished and no reply comes, so the after clause runs.
-
What does this program print?
defmodule C do def start, do: spawn(fn -> loop(0) end) def bump(pid), do: send(pid, :bump) def get(pid) do send(pid, {:get, self()}) receive do {:value, n} -> n end end defp loop(n) do receive do :bump -> loop(n + 1) {:get, from} -> send(from, {:value, n}); loop(n) end end end pid = C.start() C.bump(pid) IO.puts(C.get(pid))Answer
1
One increment arrived before the question, and the loop carries the number.
-
What does a send to a process that has already finished do?
Answer
it succeeds and the message is dropped
The send is not an error, and nothing reports that the message was never read.
Article author: Arthur Isaev