Messaging Patterns LabPython · ZeroMQ

Chapter 12

Receive without blocking

Distinguish no message from a message with zero bytes.

What you’ll learn

Use the output to tell whether a receive got a message or would have had to wait.

Prerequisite: How does a late reader catch up?. Course map →

The situation

A UI worker must remain responsive when there is no work. An empty receive should not be confused with an empty application message.

The DONTWAIT flag asks the receive to return immediately. If no message is available, PyZMQ reports zmq.Again (ZeroMQ error EAGAIN). A successful receive may give a message with zero bytes, written b'' in Python.

An empty queue and an empty message are different
  1. First receiveDONTWAITNo message is ready.
  2. Socket resultEAGAINNo receive completed.
  3. Later sendworkA message becomes available.
  4. Next receivework receivedA successful receive returns its bytes.

Conceptual diagram. EAGAIN reports that no message was ready when the receive ran.

Before you run

Is zmq.Again evidence that the peer has failed?

Run the experiment

The receiver first checks its empty queue with DONTWAIT. A sender then sends work, and the receiver reads it.

For the original example, click Restore code if it is shown, then click Run. Compare your output with the worked result.

Python prepares in the background while you read. First use can download about 71 MiB. Your code runs only when you select Run; each run starts with clean experiment state.

Your edits are saved in this browser when storage is available.

Troubleshooting

If Python stops responding, restart the environment and try again. Your code and last completed result are kept.

Downloads

Worked result

empty_receive_would_block is true on the first attempt. The value of later_message is work after a send.

Full output from the original example
{
  "empty_receive_would_block": true,
  "later_message": "work"
}

The build ran the original editor code to produce this output.

Try one change

Replace the last line in the editor with result = nonblocking(message=b''). Click Run again. Compare empty_receive_would_block and later_message. How can you tell an empty message arrived?

Inspect the socket implementation

The editor calls this read-only helper. Read all socket helpers or read the separate-process code. The code download includes both files.

def nonblocking(message=b'work'):
    with lab() as socket:
        sink=socket(zmq.PULL);source=socket(zmq.PUSH);sink.bind('inproc://empty');source.connect('inproc://empty')
        try:sink.recv(zmq.DONTWAIT);empty=False
        except zmq.Again:empty=True
        source.send(message);value=sink.recv().decode()
        return {'empty_receive_would_block':empty,'later_message':value}
Costs, waiting and recovery
AspectWhat to account for
WorkChecking repeatedly takes CPU time even when there is nothing to read.
Stored informationChoosing DONTWAIT leaves the queue’s size and contents as they are.
Message pathThe empty attempt returns no message.
WaitingUse a readiness signal or a time limit to decide when to check again.
RecoveryRepeated sends and repeated receive attempts have different effects. Check the outcome before repeating a send.

Check your understanding

What should a worker do between receive attempts if there is no work available?

Show hints
  1. Hint 1

    What would let the worker wait until a message is available?

  2. Hint 2

    What keeps a waiting worker able to shut down?

Show explanation

Wait for a signal that the socket is ready. Use a poll call with a time limit so the worker can also handle shutdown. A loop that checks constantly spends CPU time even when no work arrives.

ReferencesFunction documentation and helper source

References open in a new tab; course helpers are documented separately from library APIs. PyZMQ API links use version 27.3.0.

  • Nonblocking receive and Again

    Read the exception raised when no message can be received immediately.

  • Course helper implementation

    These are functions written for this course, not additional library APIs. Inspect their parameters, operator calls and authored policies. The source shown is generated from the same Python files packaged with Run and Download Python.

Experiment scope

The first receive uses DONTWAIT. The second waits for a message and has a five-second socket timeout.

ZeroMQ reference · Runtime and model boundaries