1 """A very simple co-routine scheduler.
2 Note: this is written to favour simple code over performance.
3 """
4 from types import coroutine
5
6
7 @coroutine
8 def switch():
9 yield
10
11
12 def run(coros):
13 """Execute a list of co-routines until all have completed."""
14 # Copy argument list to avoid modification of arguments.
15 coros = list(coros)
16
17 while len(coros):
18 # Copy the list for iteration, to enable removal from original
19 # list.
20 for coro in list(coros):
21 try:
22 coro.send(None)
23 except StopIteration:
24 coros.remove(coro)
25
26 async def coro1():
27 print("C1: Start")
28 await switch()
29 print("C1: a")
30 await switch()
31 print("C1: b")
32 await switch()
33 print("C1: c")
34 await switch()
35 print("C1: Stop")
36
37
38 async def coro2():
39 print("C2: Start")
40 await switch()
41 print("C2: a")
42 await switch()
43 print("C2: b")
44 await switch()
45 print("C2: c")
46 await switch()
47 print("C2: Stop")
48
49
50 run([coro1(), coro2()])