ELIXIR / CHAPTER 10

Processes and explicit messages

Advanced

Send a result to the intended process and receive it by shape.

By the end of this chapter

  • Capture the caller PID before spawning
  • Send a tagged result message
  • Receive only the matching message shape

The idea

Enter with anonymous functions and tuple patterns understood. Elixir processes are lightweight execution units with independent mailboxes. spawn starts a process and returns its PID. send delivers a message asynchronously, while receive selects a matching message from the current process’s mailbox. A process does not share mutable variables with its caller, so coordination uses messages rather than updates to a common variable.

self returns the PID of the process executing it. Capture the parent PID before spawning when a worker must reply to its caller; calling self inside the worker would name the worker instead. Tagged tuples identify the kind of result being delivered. Production request-response designs also need timeouts and correlation identifiers when several replies may overlap. This chapter uses one worker and one explicitly matched reply.

Elixir example
parent = self()
spawn(fn -> send(parent, {:result, 6 * 7}) end)
receive do
  {:result, value} -> IO.inspect(value)
end
Result
42

The worker sends its result to the captured parent PID. The parent waits for the matching tuple before printing.

Try it yourself

Add a receive timeout that reports no reply without claiming the worker must have failed.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

Where should parent = self() execute if a spawned worker must reply to its creator?