Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 36 ยท Processes and Message Passing

Processes and spawn

Learn how Erlang processes work: spawn, self, process identifiers, isolation, cheap creation, and why millions of processes can run on one machine.

Concurrency is the reason Erlang exists. Instead of threads that share memory and fight over locks, an Erlang program is made of thousands or millions of tiny processes. Each one has its own heap, its own mailbox and its own failures. Nothing is shared; processes only talk by sending copies of data to each other.

These are not operating system processes. They are managed by the Erlang virtual machine (the BEAM), which schedules them on a few real threads. A new process costs roughly a kilobyte of memory and a few microseconds, so you create them freely: one per connection, one per job, one per game player.

Erlang is not installed on this site, so the erlang blocks below are read-only. Next to them you will find small JavaScript stand-ins, clearly labelled, that mimic the behaviour of mailboxes so you can experiment in the browser.

Starting a process with spawn

spawn/1 takes a fun and starts it in a new process. It returns right away with the process identifier (pid) of the child; the child runs on its own.

ERLANG
1> Pid = spawn(fun() -> io:format("hello from ~p~n", [self()]) end).
hello from <0.90.0>
<0.90.0>

self/0 returns the pid of the calling process. The shell itself is a process too, so self() in the shell shows the shell's pid. A pid prints as three numbers such as <0.90.0>; you never construct one by hand, you only receive them from spawn, self or messages.

There are other forms:

ERLANG
spawn(Module, Function, Args)   % start Module:Function(Args...) in a new process
spawn_link(Fun)                 % spawn and link both ways (see the fault tolerance chapter)
spawn_monitor(Fun)              % spawn and get notified when it ends

Prefer spawn(Module, Function, Args) for code that must survive a hot code upgrade, because it always calls the newest loaded version of the function. A fun keeps pointing at the code version in which it was created.

A process ends when its function returns

There is no join or stop call. A process lives until the function it started returns, or until it crashes. Its memory is then reclaimed immediately. You can ask whether a pid is still alive:

ERLANG
1> P = spawn(fun() -> ok end).
<0.95.0>
2> timer:sleep(50), is_process_alive(P).
false

A crash in one process does not take down the others. That is the base of "let it crash": a failing process is isolated, and another process (a supervisor) decides what to do. You will build this in links, monitors and exit signals.

No shared state

Variables in Erlang are immutable, and the fun you give to spawn gets a copy of every variable it closes over. The child cannot change the parent's data, and the parent cannot change the child's.

ERLANG
start() ->
    Counter = 0,
    spawn(fun() ->
        NewValue = Counter + 1,      % works on its own copy
        io:format("child sees ~p~n", [NewValue])
    end),
    io:format("parent still has ~p~n", [Counter]).

Whatever the child learns it must send back as a message. That is the topic of the next lesson, sending and receiving.

What makes an Erlang process special

Lightweight About 1 KB at start
Isolated Own heap, no shared memory
Has a mailbox Messages queue up
Fails alone A crash stays local

Four properties that the rest of this chapter builds on.

1 / 2

Scheduling and fairness

The BEAM runs one scheduler per CPU core. Each scheduler takes processes from a run queue and lets each run for a budget of about 4,000 "reductions" (roughly function calls), then moves on to the next. A busy loop therefore cannot starve its neighbours, and even a tight infinite loop in one process leaves the others responsive. This is preemptive scheduling, unlike a JavaScript event loop where a long task blocks everything.

You can count processes and look at limits:

ERLANG
1> length(processes()).
52
2> erlang:system_info(process_limit).
1048576

The default limit is about a million and can be raised with the +P emulator flag. The numbers printed on your machine will differ.

Experiment: a tiny process model in JavaScript

JavaScript has no processes, so this stand-in uses async functions. Each "process" has a pid and runs independently; the parent keeps going without waiting. This is not Erlang and has no preemption; it only shows the shape of spawn and self.

JS Stand-in: spawn and self

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The parent line prints first, exactly as it would in Erlang: spawn returns without waiting for the child's work.

Many processes

The cheapness of processes changes how you design programs. This stand-in starts 10,000 "processes" and counts how many finished. In real Erlang the same loop with spawn runs in a few milliseconds.

JS Stand-in: ten thousand processes

Press Run (or Ctrl + Enter) to see the console output here.

No output.

In Erlang you would write it as a list comprehension:

ERLANG
Pids = [spawn(fun() -> ok end) || _ <- lists:seq(1, 10000)].

Common mistakes

  • Trying to share a variable by assignment inside the fun. The child only gets a copy.
  • Expecting spawn to return the child's result. It returns a pid; use messages for results.
  • Using a fun in code that you plan to hot-upgrade; use spawn/3 with module, function and arguments.
  • Starting a process and forgetting about it. Unsupervised processes that fail are silently lost; use links or supervisors.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does spawn/1 return?

    spawn returns immediately with the new process's pid; the child runs concurrently.
  2. 2. What happens to variables a fun captures when it is run in a new process?

    Processes share nothing; closed-over data is copied into the child.
  3. 3. When does a process end?

    A process lives until its function returns or an uncaught error kills it. Parents ending do not kill children unless they are linked.
  4. 4. Why does a runaway loop in one process not freeze the whole system?

    Each scheduler gives every process a small reduction budget, then switches to the next.

Summary

  • Erlang programs are made of many small, isolated, cheap processes.
  • spawn/1 and spawn/3 start a process and return its pid; self/0 returns your own.
  • A process ends when its function returns or it crashes, and a crash stays local.
  • Processes share no memory; closed-over values are copied.
  • The BEAM schedules processes preemptively, so one busy process cannot block the rest.

Next: Sending and receiving