Message Passing in Elixir
Message Passing with Send and Receive: What You’ll Learn
In the previous lesson, you spawned processes and saw them run concurrently. As a quick reminder, spawn starts a new lightweight process that runs an anonymous function without blocking the main process. In this lesson, you will make those processes talk to each other using send and receive. You will learn how a process listens for messages, how it matches different message shapes, and how it stays alive using recursion.
Building a Listener That Handles Messages
Explanation:
receiveblocks until a message arrives in the process mailbox.- Pattern matching routes messages to the right clause:
{:hello, name}and{:goodbye, name}are tuples; thenameis bound and printed.- After each handled message (except
:stop),listen()is called again to keep the process alive.
:stopprints a message and then returns, ending the loop and the process.
Spawning the Listener and Sending Messages
Explanation:
spawnstarts the listener in a new process and returns itspid(process identifier).send(pid, message)delivers messages asynchronously to that process’s mailbox.- Messages sent to a process are placed in its mailbox in the order they arrive (FIFO). However, when
receiveis called, it scans the mailbox for the first message that matches any of its patterns. This means a later matching message can be handled before an earlier non-matching one. Messages from multiple senders can interleave, so the order in which messages are handled depends on both arrival order and pattern matching. :stoptells the listener to print a final line and exit.Process.sleep(1000)keeps the main process alive briefly so you can see all output before the program ends.
