Python 协程asyncio 主动切换任务

协程

关于

简而言之就是在一个线程里面"并发"运行多个任务, 主要依靠来回在任务之间切换.
参考文章

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

舒服了

没事就看官方文档

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值