27/28
Part 6 of 6 · Follow-upsLearn and do

Priorities go in front of the enqueue number

"Some tasks are urgent. How would you add priorities?" This one is quick if you built the ready heap on a key.

The heap already orders by a tuple: (enqueue number, task id). Put the priority in front: (-priority, enqueue number, task id). Python compares tuples one item at a time, so the priority decides first, and the enqueue number breaks ties. The minus sign makes a higher priority come out first from a min-heap.

Then say what it costs. A low-priority task can wait forever while urgent tasks keep coming. That's called starvation. The usual fix is aging: a task's priority rises the longer it waits. And a retried task keeps its priority and its enqueue number, for the same reason it kept its place in part 2.

Predict

Waiting: a with priority 1, b with priority 5, c with priority 5, enqueued in that order. Which goes first?

Pick an answer above to see the rest