spawn and receive in Elixir
One worker process, one message home: the mailbox model in thirteen lines.
# Every process owns a mailbox; send drops a message in, receive waits.
parent = self()
spawn(fn ->
Process.sleep(50)
send(parent, {:done, "hull scrubbed"})
end)
receive do
{:done, chore} -> IO.puts("worker reports: #{chore}")
after
1_000 -> IO.puts("no word from the worker")
end
How it works
self()captures the parent's pid so the worker knows where to write.spawnstarts a process that sleeps, then sends a tagged tuple home.receiveblocks until the pattern matches;aftergives up at one second.
Keywords and builtins used here
IOProcessafterdoendfnreceive
The run, in numbers
- Lines
- 13
- Characters to type
- 282
- Tokens
- 61
- Three-star pace
- 70 tpm
At the three-star pace of 70 tokens a minute, this run takes about 52 seconds.
Step 1 of 3 in Processes, step 22 of 27 in Language basics.