typestar

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

  1. self() captures the parent's pid so the worker knows where to write.
  2. spawn starts a process that sleeps, then sends a tagged tuple home.
  3. receive blocks until the pattern matches; after gives up at one second.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 3 in Processes, step 22 of 27 in Language basics.

← Previous Next →