【Python】async和await

协程(异步)

python中为了提高I/O效率,使用协程去处理异步程序,协程自动完善了上述的各种调度任务!

  1. 进程和线程是计算机提供的,协程是程序员创造的,不存在于计算机中。
  2. 协程(Co-routine),也可称为微线程,或非抢占式的多任务子例程,一种用户态的上下文切换技术(通过一个线程实现代码块间的相互切换执行)
  3. 意义:在一个线程(协程)中,遇到io等待时间,线程可以利用这个等待时间去做其他事情。

async

  • 协程函数:定义函数时加上async修饰,即async def func()
  • 协程对象:执行协程函数得到的对象

注:执行协程函数得到协程对象,函数内部代码不会执行

# python 源码
>>> import asyncio

>>> async def main():
...     print('hello')
...     await asyncio.sleep(1)
...     print('world')

>>> main()
<coroutine object main at 0x1053bb7c8>

>>> asyncio.run(main())
hello
world

  • 执行协程函数内部代码,必须把协程对象交给事件循环处理

await

  • await + 可等待对象(协程对象,Future,Task对象(IO等待))
  • 等待到对象的返回结果,才会继续执行后续代码
# python 源码
import asyncio
import time

async def say_after(delay, what):
    await asyncio.sleep(delay)
    print(what)

async def main():
    print(f"started at {time.strftime('%X')}")

    await say_after(1, 'hello')
    #await say_after(1, 'hello')执行完之后,才继续向下执行
    await say_after(2, 'world')

    print(f"finished at {time.strftime('%X')}")

asyncio.run(main())

asyncio.create_task()

  • asyncio.create_task()作为异步并发运行协程的函数Tasks。
  • 将协程添加到asyncio.create_task()中,则该协程将很快的自动计划运行
# python 源码
async def main():
    task1 = asyncio.create_task(
        say_after(1, 'hello'))

    task2 = asyncio.create_task(
        say_after(2, 'world'))

    print(f"started at {time.strftime('%X')}")

    # Wait until both tasks are completed (should take around 2 seconds.)
    # 两个任务同时执行,直到到所有任务执行完成。
    await task1
    await task2

    print(f"finished at {time.strftime('%X')}")

原文链接:https://blog.csdn.net/qq_43380180/article/details/111573642

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值