- 引入 asyncio 模块
import asyncio
- 定义一个协程函数
async def do_something(x):
print('waiting: ', x)
await asyncio.sleep(x)
return x
- 协程不能直接运行,把协程加入到事件循环(loop)。
asyncio.get_event_loop
方法可以创建一个事件循环,然后使用run_until_complete
将协程注册到事件循环,并启动事件循环。
使用asyncio.ensure_future(coroutine)
创建 task ,方便在后面读取任务结果
coroutine1 = do_something(1)
coroutine2 = do_something(4)
tasks = [
asyncio.ensure_future(coroutine1),
asyncio.ensure_future(coroutine2)
]
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))
- 获取 task 执行结果,并打印
for task in tasks:
print('task result: ', task.result())
main.py 完整例子
import asyncio
import time
print('1')
now = lambda: time.time()
async def do_something(x):
print('waiting: ', x)
await asyncio.sleep(x)
return x
start = now()
print('2')
coroutine1 = do_something(1)
coroutine2 = do_something(4)
tasks = [
asyncio.ensure_future(coroutine1),
asyncio.ensure_future(coroutine2)
]
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))
print('123')
time.sleep(10)
print('333333')
for task in tasks:
print('task result: ', task.result())
print('time: ', now() - start)
网友评论