Concurrency · 6 / 15 Exercise Easy

Round-robin tasks

Objective

Create a Python program that shares time between several tasks in turns (round-robin), as a task scheduler does. Each task is a generator: it runs one step and hands over control with yield.

Instructions

  • Write the generator task(name, steps): for each i from 1 to steps it shows name: step i and does yield; when it ends it shows name: finished.
  • Read n and then n lines with name steps. Create the tasks and store them in a queue (collections.deque).
  • While there are tasks: take the first one, advance it one step with next() and, if it has not finished, put it back at the end of the queue. If it raises StopIteration, it has finished and is not put back.
Input
2
a 2
b 3
Output
a: step 1
b: step 1
a: step 2
b: step 2
a: finished
b: step 3
b: finished

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

Start exercise