import asyncio @asyncio.coroutine def common_generator(id): for i in range(0, 5): yield from asyncio.sleep(1) print("the id is :", id) def test_coroutine(id): yield from common_generator(id) loop = asyncio.get_event_loop() task = [test_coroutine(1), test_coroutine(2),test_coroutine(3)] loop.run_until_complete(asyncio.wait(task))loop.close()
python3.4里面,可以使用asyncio实现协程。实现协助,调用loop.run_until_complete(asyncio.wait(task))需要满足一下条件
1、传递的class必须是coroutine,自身是coroutine或者yield from一个coroutine
2、如果不加入yield from asyncio.sleep(1),那么task的任务会随机执行(不确定是什么执行顺序,好像有一点规律)