Exercise 1: Interleaving Publishing and Consuming — Possible Solution ==================================================================== THE SEQUENCE ------------------------------ q.publish('order-0'); q.publish('order-1'); q.publish('order-2') first = q.messages.pop(0) # consume just 1, manually h(first) q.publish('order-3'); q.publish('order-4') q.consume_all(h) # consume the rest RESULTS AT EACH STEP ------------------------------ after consuming 1: ['order-0'] | remaining queued: ['order-1', 'order-2'] queue after publishing 2 more: ['order-1', 'order-2', 'order-3', 'order-4'] final processed order: ['order-0', 'order-1', 'order-2', 'order-3', 'order-4'] Consuming one message correctly processed order-0 and left order-1 and order-2 still queued. Publishing two more messages while the queue already had unconsumed items correctly appended them to the END of the existing queue, not inserted anywhere else. The final consume_all() call correctly processed the remaining four messages in the exact order they were published: order-1, order-2 (published first, before the pause), then order-3, order-4 (published after). WHY THIS CONFIRMS GENUINE FIFO ORDERING ACROSS INTERLEAVED OPERATIONS ------------------------------ This chapter's own original example published all 5 messages before any consumption happened at all. This exercise interleaves publishing and consuming - proving the queue's own ordering guarantee (first published, first processed) holds even when production and consumption happen in an interleaved, unpredictable sequence, not just in the clean "publish everything, then consume everything" case. This matters because a real system's producer and consumer genuinely run independently, and this exercise confirms the queue's own ordering doesn't depend on them running in any particular relative rhythm. WHY THIS WORKS AS AN ANSWER ------------------------------ The sequence directly interleaves publish and consume calls using this chapter's own MessageQueue unmodified, and the queue's own contents and the final processed order are checked at each individual step rather than only at the end, confirming the ordering guarantee holds throughout, not just in the final result.