Syllabus Lesson 48 of 141 · Borrowed machines
Borrowed machines

Borrow triage: ordering a job queue

Why it matters "Use a priority queue" is the reflex for any queue with priorities. It answers "who matters most?" when the real question is often "who can wait least?". Other fields have been answering that question for a long time.

Three desks

A hospital emergency department. A triage nurse puts each arrival into a category, and each category has a target time to be seen: in the widely used Manchester system, immediately, within 10 minutes, 60, 120 or 240. When a doctor is free, the next patient is not simply the sickest in the room: a standard patient about to pass their target can go before an urgent one who arrived a minute ago and still has time.

Airport check-in. There are separate lanes for premium and economy. Within a lane, people are served in order of arrival. But when a flight is about to close, staff walk the economy line calling that flight forward, ahead of premium passengers whose flights leave later.

A library returns desk. One line, served strictly in order. Nobody is ever overtaken, and nobody's urgency is considered.

Compare before you code

  1. In each desk, what decides who is served next?
  2. Which desks can make someone wait for ever? Which can make an urgent case wait too long?
  3. The hospital and the airport look nothing alike. What do they share? Write it as one sentence that mentions neither hospitals nor planes.
  4. In the airport, why is it enough to look at the front of each lane?

The target

A background job system runs on one worker that takes exactly one minute per job. Jobs are interactive (priority 1), standard (2) or batch (3), and each priority has a service promise: the longest a job of that priority may wait before it starts. The current scheduler always runs the highest priority waiting job, and batch jobs miss their promise every afternoon.

Your turn

Write order(jobs, max_wait). jobs is a list of {"id", "arrive", "priority"} sorted by arrive (whole minutes); max_wait maps priority to the most minutes a job may wait. Return the job ids in the order the worker runs them. The worker runs one job per minute: a job starts at the later of its arrival and the end of the previous job, and its wait is start minus arrival. Rule: no job may wait longer than max_wait[priority]. The test days can all be served with no job late; with {1: 3, 2: 20, 3: 60} a day has about 1,000 jobs.

Spotted a problem in this lesson? Report it · Ask about this lesson

This exercise opens soon

Finish the lesson before it and this one unlocks. The whole course is free, no account needed, and you can read this lesson right now.