Concurrency · 13 / 15 Exercise Hard

Event loop with a virtual clock

Objective

This is how asyncio.sleep works inside: an event loop keeps a schedule of sleeping tasks and always wakes up the one that is due first. Write one with a virtual clock: tasks are generators that yield with yield the number of units they want to sleep. Real threads cannot be created in the browser, so the program simulates the situation in a deterministic way.

Instructions

  • Read n and then n lines with name pause1 pause2 ... (each task has at least one pause, in whole units).
  • Each task is a generator: for each pause it does yield pause and, when it is woken up, it shows t=T name wakes up (pause i) (where T is the clock and i the pause number).
  • Use a schedule with heapq of tuples (time, order, generator): the wake-up time, the creation order (breaks ties) and the generator.
  • The clock starts at 0. Take from the schedule the task that wakes up first, set the clock to that time, resume it with next() and schedule it again with its next pause (if any).
Input
2
a 3 2
b 1 1 4
Output
t=1 b wakes up (pause 1)
t=2 b wakes up (pause 2)
t=3 a wakes up (pause 1)
t=5 a wakes up (pause 2)
t=6 b wakes up (pause 3)

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise