🎓 A1Learner
🔍
0 of 54 lessons completed

Elixir Processes

A process is an independent line of execution that runs code on its own. A program can run many processes at the same time.

Spawn returns a PID

The new process runs the anonymous function on its own and prints nothing. The main code only checks the value spawn returned.

pid = spawn(fn -> 6 * 7 end)
IO.puts(is_pid(pid))

A waiting worker stays alive

This worker waits inside receive for a message and then loops to wait again. Because it is still waiting, it is still alive.

defmodule Worker do
  def loop do
    receive do
      _ -> loop()
    end
  end
end

pid = spawn(Worker, :loop, [])
IO.puts(Process.alive?(pid))

Your own PID differs from a spawned one

self() gives the PID of the process running this script. A spawned process always has a different PID.

IO.puts(is_pid(self()))
pid = spawn(fn -> 2 + 3 end)
IO.puts(pid != self())

Example

defmodule Worker do
  def loop do
    receive do
      _ -> loop()
    end
  end
end

first = spawn(Worker, :loop, [])
second = spawn(Worker, :loop, [])
IO.puts(Process.alive?(first))
IO.puts(Process.alive?(second))

Key points

  • PID: the value that identifies one process, like an address for it.
  • Spawn: spawn starts a new process running a function and returns its PID.
  • Self: self() returns the PID of the process running the current code.
  • Check: is_pid(value) returns true when the value is a PID.
  • Liveness: Process.alive?(pid) returns true while that process is still running.
  • Independence: after spawn, the starting code continues without waiting for the new process to finish.

In this example, two workers are spawned from the same loop function, and each one waits for a message. Both alive checks print true, which shows both processes are running at the same time. Sending them messages is the topic of the next lesson.

Note

Elixir processes are light, and one program can run thousands of them at once.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does spawn return?