def test1():
for i in range(10):
print('-----1-----')
yield
def test2():
for i in range(10):
print('-----2-----')
yield
def main():
t1 = test1()
t2 = test2()
# 借用while循环+yield生成器的特点,从而实现了多任务,
while True:
try:
# 始终要记得,生成器要使用next来调用
# 当调用next(t1)时,遇到yield时,就会暂停而等待下一次的调用.
next(t1)
# 当调用next(t2)时,遇到yield时,就会暂停而等待下一次的调用.
next(t2)
except StopIteration:
break
if __name__ == '__main__':
main()
执行的结果为:
-----1-----
-----2-----
-----1-----
-----2-----
-----1-----
-----2-----
-----1-----
-----2-----
-----1-----
-----2-----
-----1-----
-----2-----
-----1-----
-----2-----
-----1-----
-----2-----
-----1-----
-----2-----
-----1-----
-----2-----
Process finished with exit code 0