Mailbox Management

Understand what a mailbox of a thread is, and how it is maintained.

We'll cover the following

Using the mailbox

Every thread has a private mailbox that holds the messages that are sent to it. The number of messages in a mailbox may increase or decrease depending on how long it takes for the thread to receive and respond to each message. A continuously growing mailbox puts stress on the entire system and may point to a design flaw in the program. It may also mean that the thread may never get to the most recent messages.

setMaxMailboxSize() is used for limiting the number of messages that a mailbox can hold. Its three parameters specify the mailbox, the maximum number of messages that it can hold, and what should happen when the mailbox is full, in that order. There are four choices for the last parameter:

  1. OnCrowding.block: The sender waits until there is room in the mailbox.

  2. OnCrowding.ignore: The message is discarded.

  3. OnCrowding.throwException: A MailboxFull exception is thrown when sending the message.

  4. A function pointer of type bool function(Tid): The specified function is called.

Before seeing an example of setMaxMailboxSize(), let’s first cause a mailbox to grow continuously. The worker in the following program sends messages back to back, but the owner spends some time for each message:

Get hands-on with 1200+ tech skills courses.