Processes and message passing
| spawn | |
| Send with ! | |
| receive ... end | |
| The mailbox |
spawn
The spawn function starts a new process and answers its process identifier, a pid. The process runs a fun and shares nothing with the caller.
The new process has its own heap and its own stack, so a crash inside it never corrupts the caller.
1> Pid = spawn(fun() -> io:format("hi~n") end).
hi
<0.84.0>
2> is_pid(Pid).
true
Send with !
The exclamation mark sends a message to a pid. The message is any term, and the sender never waits: send is a fire-and-forget step.
The message lands in the receiver's mailbox, in the order it arrived.
1> Pid ! {greet, "Ada"}.
{greet,"Ada"}
2> self().
<0.82.0>
receive ... end
The receive expression waits for a mailbox message that matches one of its patterns. The first match runs its body; the rest stay queued.
A timeout after the patterns answers after the milliseconds you give it, so receive never blocks forever.
loop() ->
receive
{greet, Who} ->
io:format("hello ~s~n", [Who]);
stop --> ok
end,
loop().
The mailbox
Every process owns a mailbox. Sending never fails, even when the receiver is busy or has crashed, and the message is copied to the receiver.
receive picks messages selectively, which means a process can skip over messages that do not match yet.
Next: Spawn and links
Article author: Arthur Isaev