Lesson 8: Introduction to Processes
Spawn lightweight Erlang processes, identify them by pid, and see why a crash in one process leaves the others running
Lesson 07 introduced βlet it crashβ and said that a failing process can be restarted by something else. That only works if a crash stays contained. Processes are the unit of containment in Erlang. Every piece of running code lives in one, including the shell you have been typing into.
What a Process Is
An Erlang process is not an operating system process or thread. The Erlang VM creates and schedules processes itself. It starts one scheduler thread per CPU core, and each scheduler runs many Erlang processes in turn, giving each a short slice of work before switching to the next. No process can hog a core, so one slow chat user cannot freeze the others.
Each process has its own small heap and stack. Processes share no memory. A variable bound in one process cannot be read or changed by another. The only way to get data from one process to another is to send a copy of it as a message. No shared memory means no locks, and it means a process can die without leaving corrupted data behind for others.
A new process starts with a few kilobytes of memory, so a system can run hundreds of thousands of them. That changes how you design programs. You do not pool processes or ration them. You create one for each independent activity.
Spawning a Process
spawn/1 takes a fun, starts a new process that runs it, and returns right away with a process identifier, or pid.
1> self().<0.84.0>2> Pid = spawn(fun() -> io:format("Hello from ~p~n", [self()]) end).Hello from <0.87.0><0.87.0>self() returns the pid of the process that calls it. The shell is process <0.84.0>. Inside the fun, self() returned <0.87.0>, which is the same value spawn/1 handed back to the shell. Your numbers will differ. A pid is an ordinary value. You can bind it to a variable, store it in a tuple or a map, and send it to other processes.
Real programs usually spawn a function from a module with spawn/3. It takes a module name, a function name, and a list of arguments. The function must be exported.
Create greeter.erl:
-module(greeter).-export([greet/1]).
greet(Name) -> io:format("~p says hello to ~s~n", [self(), Name]).3> c(greeter).{ok,greeter}4> greeter:greet("alice").<0.84.0> says hello to aliceok5> spawn(greeter, greet, ["alice"]).<0.96.0> says hello to alice<0.96.0>Calling greeter:greet/1 directly runs it in the shell process. Spawning it runs the same code in a new process. Code does not belong to a process. Any process can run any function.
Processes End When Their Function Returns
A process lives exactly as long as the function it was spawned with. When that function returns, the process is gone and its memory is freed. is_process_alive/1 tells you which state a pid is in.
6> Sleeper = spawn(fun() -> timer:sleep(5000), io:format("done~n") end).<0.98.0>7> is_process_alive(Sleeper).true8> timer:sleep(5100).doneok9> is_process_alive(Sleeper).falsetimer:sleep/1 suspends only the calling process. The shell stayed usable while Sleeper slept. A process that should stay around, like a chat connection, runs a function that loops. Lesson 09 builds those loops.
Getting a Result Back
The return value of a spawned function is thrown away. Nothing is waiting for it.
10> spawn(fun() -> 21 * 2 end).<0.103.0>The 42 went nowhere. To get a result out, the new process has to send it as a message. Pid ! Message sends, and receive waits for a message and pattern matches on it.
11> Shell = self().<0.84.0>12> spawn(fun() -> Shell ! 21 * 2 end).<0.106.0>13> receive Answer -> Answer end.42We bind Shell first because self() inside the fun would be the pid of the new process. The fun captures Shell in its closure, as funs did in lesson 04.
Tagging the message with the senderβs pid tells the receiver who answered.
14> spawn(fun() -> Shell ! {self(), lists:sum(lists:seq(1, 1000000))} end).<0.109.0>15> receive {From, Sum} -> {From, Sum} end.{<0.109.0>,500000500000}That is all the message passing this lesson needs. Lesson 09 covers mailboxes, timeouts, and receive loops.
Spawning 100,000 Processes
timer:tc/1 runs a fun and returns the elapsed microseconds with the result. Weβll use it to measure what a process costs.
Create spawn_bench.erl:
-module(spawn_bench).-export([run/1, wait/0]).
run(N) -> Before = erlang:memory(processes), {Micros, Pids} = timer:tc(fun() -> spawn_many(N) end), After = erlang:memory(processes), io:format("Spawned ~p processes in ~p ms~n", [N, Micros div 1000]), io:format("~p microseconds per process~n", [Micros / N]), io:format("~p bytes per process~n", [(After - Before) div N]), io:format("Processes alive: ~p~n", [erlang:system_info(process_count)]), [Pid ! stop || Pid <- Pids], ok.
spawn_many(N) -> [spawn(?MODULE, wait, []) || _ <- lists:seq(1, N)].
wait() -> receive stop -> ok end.Each process blocks in receive until it gets stop, so all of them are alive when we count. A process waiting in receive uses no CPU. The scheduler skips it until a message arrives.
16> c(spawn_bench).{ok,spawn_bench}17> spawn_bench:run(100000).Spawned 100000 processes in 63 ms0.63584 microseconds per process2680 bytes per processProcesses alive: 100044ok18> erlang:system_info(process_limit).1048576Under a microsecond and about 2.7 KB each on this machine. The extra 44 processes are the shell and the VMβs own system processes. The default limit is about a million and the +P flag to erl raises it.
Isolation
Start one process that takes three seconds to finish and another that crashes right away.
19> Survivor = spawn(fun() -> timer:sleep(3000), io:format("still here~n") end).<0.100120.0>20> Crasher = spawn(fun() -> 1 / 0 end).<0.100122.0>=ERROR REPORT==== 19-Sep-2026::10:10:45.490108 ===Error in process <0.100122.0> with exit value:{badarith,[{erlang,'/',[1,0],[{error_info,#{module => erl_erts_errors}}]}]}
21> is_process_alive(Crasher).false22> is_process_alive(Survivor).true23> timer:sleep(3100).still hereokThe uncaught error killed Crasher and the VM logged a report. Nothing else happened. Survivor and the shell kept running. They had no memory in common with Crasher, so there was nothing for the crash to damage.
This is what makes βlet it crashβ from lesson 07 practical. A process that hits a bug takes only its own state down with it. You do not need try ... catch around everything to protect the rest of the system. The process boundary already does that.
The shell follows the same rule. An error in a shell expression kills the shell process, and a fresh one replaces it.
24> self().<0.84.0>25> 1 / 0.** exception error: an error occurred when evaluating an arithmetic expression in operator '/'/2 called as 1 / 026> self().<0.100130.0>The pid changed. Something noticed the dead shell and started a new one. Lesson 10 shows how one process can detect that another has died.
One Process per User
The chat server will give every connected user a process of their own. That process owns the userβs socket and handles their messages. Because processes are cheap, ten thousand users means ten thousand processes, and the VM spreads them across all cores. Because processes are isolated, a malformed message that crashes one userβs process disconnects that user and nobody else. Because each process handles one user, its code reads like a sequential program with no callbacks and no locks.
Exercises
Exercise 1: Parallel Squares
Write squares:start/1. It takes a list of numbers and spawns one process per number. Each process prints its own pid and the square of its number. Run it a few times and watch the order of the output.
-module(squares).-export([start/1, square/1]).
start(Numbers) -> % spawn squares:square/1 for each number ok.
square(N) -> % print self() and N * N ok.
% Expected: squares:start([1, 2, 3]) prints three lines such as% <0.95.0>: 1% <0.96.0>: 4% <0.97.0>: 9Exercise 2: Collect the Results
Change exercise 1 so each process sends {self(), N * N} back to the process that called start/1. Receive one message per spawned pid and return the squares in the original order. Match on each pid in turn inside the receive pattern.
collect(Pids) -> % for each Pid: receive {Pid, Square} -> Square end [].
% Expected: squares:start([1, 2, 3]) returns [1,4,9]Exercise 3: Find the Limit
Run spawn_bench:run/1 with 10000, 100000, and 500000. Does the cost per process change? Then start the VM with erl +P 2000000 and check erlang:system_info(process_limit).
% Expected: time and memory per process stay roughly constantExercise 4: Contained Crashes
Spawn five processes from a list of inputs. Each one calls list_to_integer/1 on its input and prints the result. Make two of the inputs invalid, such as "abc".
Inputs = ["1", "abc", "3", "x", "5"].% spawn one process per input% Expected: three printed integers, two error reports, and a working shellKey Takeaways
- Processes belong to the VM, not the operating system. They start in under a microsecond and take a few kilobytes
spawn/1andspawn/3start a process and return its pid immediately without waiting for it- A pid is a plain value that you can store, compare, and send.
self()gives the calling process its own pid - A process ends when its function returns. Its return value is discarded, so results travel back as messages
- No shared memory means data moves between processes only by copying it into a message
- A crash stays inside one process, which is what makes βlet it crashβ safe
- The chat server runs one process per connected user
Interactive Koans
Koans - Test Your Understanding
Fill in the blanks and press Enter or click Run to test your knowledge!
spawn/1 returns a value right away. Which type test is true for it?
π‘ Hint
π Explanation
Which function returns the pid of the process that calls it?
π‘ Hint
π Explanation
What does is_process_alive/1 return after the spawned function has returned?
π‘ Hint
π Explanation
spawn/3 takes a module, a function name, and a list of arguments. What does the spawned process send back?
π‘ Hint
π Explanation
The first process crashes. What does the second process still deliver?
π‘ Hint
π Explanation
The spawned process sends its own pid. What does the comparison with the pid returned by spawn evaluate to?
π‘ Hint
π Explanation
Each spawned process reports in once. How many messages does the shell count?
π‘ Hint
π Explanation
Finished this lesson?
Mark it as complete to track your progress
This open source tutorial is brought to you by East Branch Software - we build reliable software systems.
Found an issue? Edit this page on GitHub or open an issue