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:

  • receive blocks until a message arrives in the process mailbox.
  • Pattern matching routes messages to the right clause:
    • {:hello, name} and {:goodbye, name} are tuples; the name is bound and printed.
    • After each handled message (except :stop), listen() is called again to keep the process alive.
  • :stop prints a message and then returns, ending the loop and the process.
Spawning the Listener and Sending Messages

Explanation:

  • spawn starts the listener in a new process and returns its pid (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 receive is 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.
  • :stop tells 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.
Summary and Next Steps

You now know how to connect processes using send and receive: spawn a process, listen with a receive loop, pattern match on message shapes, and stop cleanly. This is the foundation of Elixir’s concurrency model and a key skill for building reliable systems.

Ready to put your skills to work? Head to the practice section and try it out.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal