前言
书接上文,本文造第三个轮子,也是asyncio包里面非常常用的一个函数gather
一、知识准备
● 相对于前两个函数,gather
的使用频率更高,因为它支持多个协程任务“同时”执行
● 理解__await__
__iter__
的使用
● 理解关键字async/await,async/await是3.5之后的语法,和yield/yield from异曲同工
● 今天的文章有点长,请大家耐心看完
二、环境准备
组件 | 版本 |
---|---|
python | 3.7.7 |
三、
gather
的实现
先来看下官方gather的使用方法:
|># more main.py
import asyncio
async def hello():
print('enter hello ...')
return 'return hello ...'
async def world():
print('enter world ...')
return 'return world ...'
async def helloworld():
print('enter helloworld')
ret = await asyncio.gather(hello(), world())
print('exit helloworld')
return ret
if __name__ == "__main__":
ret = asyncio.run(helloworld())
print(ret)
|># python3 main.py
enter helloworld
enter hello ...
enter world ...
exit helloworld
['return hello ...', 'return world ...']
来看下造的轮子的使用方式:
▶ more main.py
import wilsonasyncio
async def hello():
print('enter hello ...')
return 'return hello ...'
async def world():
print('enter world ...')
return 'return world ...'
async def helloworld():
print('enter helloworld')
ret = await wilsonasyncio.gather(hello(), world())
print('exit helloworld')
return ret
if __name__ == "__main__":
ret = wilsonasyncio.run(helloworld())
print(ret)
▶ python3 main.py
enter helloworld
enter hello ...
enter world ...
exit helloworld
['return hello ...', 'return world ...']
自己造的轮子也很好的运行了,下面我们来看下轮子的代码
四、代码解析
1)代码组成
|># tree
.
├── eventloops.py
├── futures.py
├── main.py
├── tasks.py
├── wilsonasyncio.py
文件 | 作用 |
---|---|
eventloops.py | 事件循环 |
futures.py | futures对象 |
tasks.py | tasks对象 |
wilsonasyncio.py | 可调用方法集合 |
main.py | 入口 |
2)代码概览:
eventloops.py
类/函数 | 方法 | 对象 | 作用 | 描述 |
---|---|---|---|---|
Eventloop | 事件循环,一个线程只有运行一个 | |||
__init__ |
初始化两个重要对象 self._ready 与 self._stopping |
|||
self._ready |
所有的待执行任务都是从这个队列取出来,非常重要 | |||