Elixir Process Mailboxes
A process mailbox is a queue where incoming messages wait until the process reads them. Messages wait in the order they arrive.
The queue length counts waiting messages
Two messages are sent to this process before anything is read.
send(self(), :hello)
send(self(), :world)
{:message_queue_len, len} = Process.info(self(), :message_queue_len)
IO.puts(len)
receive do :hello -> :ok end
receive do :world -> :ok endMessages are read in arrival order
Three messages are sent, then read one at a time.
send(self(), :first)
send(self(), :second)
send(self(), :third)
receive do :first -> IO.puts("first") end
receive do :second -> IO.puts("second") end
receive do :third -> IO.puts("third") endReading shrinks the queue
One message is read, so two of three stay waiting.
send(self(), :a)
send(self(), :b)
send(self(), :c)
receive do :a -> :ok end
{:message_queue_len, len} = Process.info(self(), :message_queue_len)
IO.puts(len)
receive do :b -> :ok end
receive do :c -> :ok endExample
send(self(), :one)
send(self(), :two)
send(self(), :three)
{:message_queue_len, len} = Process.info(self(), :message_queue_len)
IO.puts(len)
receive do :one -> IO.puts("one") end
receive do :two -> IO.puts("two") end
receive do :three -> IO.puts("three") end
{:message_queue_len, left} = Process.info(self(), :message_queue_len)
IO.puts(left)Key points
- Mailbox: A mailbox is a queue of messages waiting for one process.
- Order: Messages from the same sender arrive in the order they were sent.
- Waiting: A message stays in the mailbox until a receive clause reads it.
- Length: Process.info with message_queue_len reports how many messages are waiting.
- Reading: A receive clause takes a message out of the mailbox when it reads it.
In this example, three messages are sent to the process itself. The queue length starts at three, each message is read in arrival order, and the queue length ends at zero.
Note
A mailbox belongs to one process, so another process cannot read its messages.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
You send two messages to your own process and read one. How many messages are waiting?