基于协程的异步编程(async-await)-2
async-await使用
什么是协程函数?
协程函数
协程函数,定义函数时async def 函数名。
协程对象,执行协程函数() 得到协程对象。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import asyncio async def async_func(): print(1) result = async_func() # 协程函数加上扩后,不会执行,只会得到一个协程对象。 # 需要通过事件循环才可以运行协程函数。 # 获取一个事件循环 loop = asyncio.get_event_loop() # 将任务放到任务列表 loop.run_until_complete(result) # asyncio.run(result) #3.7之后使用,实际简化了封装了上面这两句。 |
await使用
await 后面可以接 可等待的对象(协程对象,Future、task对象) IO等待
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 |
# 示例1 async def await_func1(): print('搞起来!') # 通过asyncio.sleep(2) 模拟遇到io情况,如果有其他任务这时线程就切换到其他任务中去干活了 # await 可以接收返回值 response = await asyncio.sleep(2) print('结束了', response) loop = asyncio.get_event_loop() loop.run_until_complete(await_func1()) # 示例2 async def await_func1(): print('搞起来!') # 通过asyncio.sleep(2) 模拟遇到io情况,如果有其他任务这时线程就切换到其他任务中去干活了 # await 可以接收返回值 await asyncio.sleep(2) return '结束了' async def await_func2(): print('执行协程函数内部代码。。。') # 通过await 调用协程对象 用上await就是等待对象的值返回后,才会继续往下走 # 这个例子中看起来用到await形成了串行的一个样子,实际async主动切换是从任务角度来的, # 也就是我们创建run_until_complete多个任务。才会相互切换 response = await await_func1() print('IO结束,', response) # 在一个函数中 可以存在多个await await 重点在与等,比如下面代码依赖上面代码的数据返回,就可以使用await response1 = await await_func1() print('IO结束,', response1) loop = asyncio.get_event_loop() loop.run_until_complete(await_func2()) |
未经允许不得转载:大师兄 » 基于协程的异步编程(async-await)-2
评论已关闭