协程
关于
简而言之就是在一个线程里面"并发"运行多个任务, 主要依靠来回在任务之间切换.
参考文章
asyncio
asyncio是一个python包, 主要用来处理python的协程任务, 相同功能的包还有其他但是这个是官方指定的.
基本用法
async def get_2():
print('5')
print('6')
print('7')
print('8')
async def get_1():
i = 10
while i < 20:
print(i)
i += 1
async def main():
task2 = asyncio.create_task(get_1())
task = asyncio.create_task(get_2())
await task2
await task
pass
asyncio.run(main())
基本用法不做过多介绍, 可以看参考文章
问题
上面的代码有一个问题, 也不是问题, 一个疑惑.
我们以为的输出是
10
5
11
6
12
7
13
8
.
.
这样才算是在任务之间切换了嘛.
但是实际是
10
11
12
13
14
15
16
17
18
19
5
6
7
8
欸, 这是为什么. 他是等待了一个函数完全执行完了才执行第二个函数.
假如我们有一个任务需要一个while True
岂不是直接阻塞
主动在任务之间切换
asyncio.sleep(delay, result=None)
函数可以帮助我们
在官方文档
将 delay 设为 0 将提供一个经优化的路径以允许其他任务运行。 这可供长期间运行的函数使用以避免在函数调用的全过程中阻塞事件循环。
所以我们可以调用await asyncio.sleep(0)
来切换任务
修改后的代码
async def get_2():
print('5')
await asyncio.sleep(0)
print('6')
await asyncio.sleep(0)
print('7')
await asyncio.sleep(0)
print('8')
async def get_1():
i = 10
while i < 20:
print(i)
await asyncio.sleep(0)
i += 1
async def main():
task2 = asyncio.create_task(get_1())
task = asyncio.create_task(get_2())
await task2
await task
pass
asyncio.run(main())
结果:
10
5
11
6
12
7
13
8
14
15
16
17
18
19
舒服了