F3.07 · part 1 of 3
Spawning a process
spawn/1 takes a function, starts it as a new process on the BEAM, and
returns a PID at once. The caller does not wait. The child runs concurrently, on its own heap, inside its own
crash boundary — the three things that make a process more than a function call.
The portal hands slow work to spawned processes so a request never blocks on it. Compare a plain call with a spawn, and see what happens to the caller when the new process crashes.
Call, spawn, or crash
A direct call runs inside the caller and blocks until it returns a value. spawn
starts a separate process and returns a PID instead, leaving the caller free. And because the child is
isolated, its crash does not reach the caller. Choose each and follow both lanes.
How the work runs · select one
The PID is the whole handle to a process. A spawn returns one even when the work later fails, and that returned address is how another process will send to it, link to it, or restart it.
The spawn primitives
A process knows its own PID through self/0, and any PID can be checked with
Process.alive?/1. A spawned process ends when its function returns — or when it
raises, without disturbing anyone else.
parent = self() # this process's own PID pid = spawn(fn -> Portal.Work.run(job) # runs in the new process end) Process.alive?(pid) # => true, until run/1 returns pid # => #PID<0.118.0>
The idea
Do slow work without making the caller wait, and keep one failure from spreading.
In Elixir
spawn returns a PID at once; the child has its own heap and crash boundary, scheduled across cores.
Next: sending and receiving messages — how an isolated process gets work in and sends results back.
References
Primary sources for this lesson, and where it connects in the course.
Sources
- Processes — Elixir documentation — spawn, send, and receive.
- Actor model — Wikipedia — the concurrency model behind isolated processes.
- Armstrong, J. (2003). Making reliable distributed systems in the presence of software errors — concurrency-oriented programming: isolation and message passing.