python协程示例

it2026-08-04  1

import time import asyncio async def hello(i): print('Hello World:%s' % time.time()) return i def run(): loop = asyncio.get_event_loop() tasks = [] for i in range(5): task = loop.create_task(hello(i)) loop.run_until_complete(task) tasks.append(task.result()) print([task for task in tasks]) # gather def run_gather(): loop = asyncio.get_event_loop() coros = [] for i in range(5): task = loop.create_task(hello(i)) coros.append(task) loop.run_until_complete(asyncio.gather(*coros)) print([coro.result() for coro in coros]) run() run_gather()
最新回复(0)