TExcelTAD
Home › Elixir › Elixir Processes

Elixir Processes

All Elixir code runs inside processes. A BEAM process is not an operating-system process or thread: it is a tiny, isolated unit with its own memory (a few kilobytes to start with) and its own mailbox. The VM schedules hundreds of thousands of them across all CPU cores. Processes share nothing; the only way to communicate is to send messages.

Primitive What it does
spawn(fun) starts a new process running fun, returns its PID
self() the PID of the current process
send(pid, message) puts message in pid's mailbox (never blocks)
receive do ... end waits for a message that matches one of the patterns
Process.alive?(pid) whether the process is still running

Spawning and sending

elixir · try it yourself
parent = self()

worker =
  spawn(fn ->
    receive do
      {:square, n, from} -> send(from, {:result, n * n})
    end
  end)

IO.inspect(is_pid(worker))
send(worker, {:square, 12, parent})

receive do
  {:result, value} -> IO.puts("Got #{value}")
end

Process.sleep(10)
IO.inspect(Process.alive?(worker))
true
Got 144
false

The worker handles exactly one message and then its function ends, so the process exits. PIDs print as #PID<0.110.0>, and the numbers change between runs, which is why this course prints is_pid/1 instead.

Note: Messages are copied into the receiving process's memory. That is what makes processes independent: a crash or a garbage collection in one never affects another.

receive: patterns and timeouts

receive looks through the mailbox for the first message that matches any of its clauses. Messages that don't match stay in the mailbox for later. An after clause gives up after a number of milliseconds:

elixir · try it yourself
send(self(), {:log, "starting"})
send(self(), {:job, 1})
send(self(), {:job, 2})

# Pick the jobs first, even though the log message arrived earlier
for _ <- 1..2 do
  receive do
    {:job, id} -> IO.puts("job #{id}")
  end
end

receive do
  {:log, text} -> IO.puts("log: #{text}")
end

receive do
  :never_sent -> IO.puts("impossible")
after
  50 -> IO.puts("no message within 50 ms")
end
job 1
job 2
log: starting
no message within 50 ms

Sending to self() is a handy way to experiment: the messages wait in your own mailbox. In a script, the main program is itself a process.

A process that keeps state

A process can keep running by calling itself recursively after handling a message. The argument of that recursive function is the process's state. This loop is the idea behind Agent and GenServer:

elixir · try it yourself
defmodule Counter do
  def start(initial), do: spawn(fn -> loop(initial) end)

  defp loop(count) do
    receive do
      :increment ->
        loop(count + 1)

      {:get, caller} ->
        send(caller, {:count, count})
        loop(count)

      :stop ->
        :ok
    end
  end
end

counter = Counter.start(10)
send(counter, :increment)
send(counter, :increment)
send(counter, :increment)
send(counter, {:get, self()})

receive do
  {:count, n} -> IO.puts("count = #{n}")
end

send(counter, :stop)
count = 13

Messages from one process to another arrive in the order they were sent, so the three increments are always handled before the :get. (There is no ordering guarantee between messages from different senders.)

Many processes, deterministic results

When you start several workers, their replies can arrive in any order. To get a predictable result, tag each reply with something you can match on and receive in the order you choose:

elixir · try it yourself
parent = self()
words = ["elixir", "erlang", "beam", "otp"]

for {word, index} <- Enum.with_index(words) do
  spawn(fn -> send(parent, {:done, index, String.upcase(word)}) end)
end

# Receive reply 0, then 1, then 2, then 3 (pinning the index)
results =
  for index <- 0..(length(words) - 1) do
    receive do
      {:done, ^index, value} -> value
    end
  end

IO.inspect(results)
["ELIXIR", "ERLANG", "BEAM", "OTP"]

Test yourself

What does send/2 do if the receiver isn't waiting in a receive?

  1. It blocks until the receiver is ready
  2. It raises an error
  3. The message waits in the receiver's mailbox
  4. The message is lost

How does a process keep state between messages?

  1. In a global variable
  2. By mutating its PID
  3. By calling its loop function recursively with the new state
  4. Processes can't have state

What does the after 100 -> clause of receive do?

  1. Runs after every message
  2. Runs if no matching message arrives within 100 ms
  3. Delays every message by 100 ms
  4. Kills the process after 100 ms