Skip to content
BytePatterns

Finish Times on a Single Event Loop

MediumConcurrency#event-loop#min-heap#event-simulation~25m

Problem

A single-threaded event loop runs async tasks. Each task is (name, arrive, steps), where steps alternates CPU time and I/O wait, starting and ending with CPU: [2, 10, 1] means run 2 ms, await I/O for 10 ms, then run 1 ms more. The loop runs one piece of CPU work at a time and never interrupts it. A task is ready when it arrives and again when its I/O completes, and the loop always picks the task that has been ready the longest, breaking ties by the order tasks are listed. When nothing is ready the loop sits idle until something is. Return a dict from task name to the time it finishes, in the order tasks finish.

Examples

Input:  [("api", 0, [2, 10, 1]), ("report", 1, [30]), ("ping", 3, [1])]
Output: {'report': 32, 'ping': 33, 'api': 34}
Why:    one 30 ms block of CPU holds up a 1 ms ping and the api's last step
Input:  [("api", 0, [2, 10, 1]), ("report", 1, [10, 0, 10, 0, 10]), ("ping", 3, [1])]
Output: {'ping': 13, 'api': 14, 'report': 34}
Why:    the same report split into three chunks with zero-length awaits lets the others in between
Input:  [("job", 5, [4, 3, 2])]
Output: {'job': 14}
Why:    edge case, with one task the loop only waits for its arrival and its own I/O

Hints

0 / 3

Stuck on the idea rather than the code? Blocking the Event Loop covers it.