Simple loop

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
def first():
for x in range(10):
print('first:',x)
yield
def second():
for x in range(10):
print('second:',x)
yield
def third():
for x in range(10):
print('third:',x)
yield
class Eventloop:
coroutines = []
def run(self):
while True:
if len(self.coroutines) == 0:
break
for coro in self.coroutines:
try:
next(coro)
except StopIteration as e:
print(coro, 'is end.')
self.coroutines.remove(coro)
def add_coroutine(self, coro):
self.coroutines.append(coro())
loop = Eventloop()
loop.add_coroutine(first)
loop.add_coroutine(second)
loop.add_coroutine(third)
if __name__ == '__main__':
loop.run()
first: 0
second: 0
third: 0
first: 1
second: 1
third: 1
first: 2
second: 2
third: 2
first: 3
second: 3
third: 3
first: 4
second: 4
third: 4
first: 5
second: 5
third: 5
first: 6
second: 6
third: 6
first: 7
second: 7
third: 7
first: 8
second: 8
third: 8
first: 9
second: 9
third: 9
<generator object first at 0x7f5a871218e0> is end.
<generator object third at 0x7f5a87121990> is end.