python的异步编程async

以你之姓@ 2024-03-24 23:50 124阅读 0赞

一、介绍

在Python 3.5中引入了async和await关键字,用于异步编程。async关键字用于定义一个协程(coroutine),而await关键字则用于等待一个协程完成。

注:协程(coroutine)是是一种轻量级的线程,但相对子线程而言,协程更为一般和灵活,在实践中没有子线程那样使用广泛。协程更适合于用来实现彼此熟悉的程序组件,如协作式多任务、异常处理、事件循环、迭代器、无限列表和管道。

二、使用

  1. 异步函数:使用async def定义的函数是异步函数。它们可以包含await关键字,以等待异步操作完成。异步函数在被调用时不会立即执行,而是返回一个协程对象。
  2. await 关键字:在异步函数中,await关键字用于暂停当前协程的执行,等待某个异步操作完成,然后再继续执行。

    import asyncio

    async def foo():

    1. print("Foo start")
    2. await asyncio.sleep(2) # 模拟耗时操作
    3. print("Foo end")

    async def bar():

    1. print("Bar start")
    2. await asyncio.sleep(1) # 模拟耗时操作
    3. print("Bar end")

    async def main():

    1. await asyncio.gather(foo(), bar()) # 并发运行foo()和bar()

    asyncio.run(main()) # Python 3.7+

14ec5ad38c984837b73ad692fb67e735.png

在上面的示例中,asyncio.run(main())会运行main()函数,而main()函数使用asyncio.gather()来并发运行foo()bar()。在foo()bar()中,await asyncio.sleep()模拟了异步操作,使得在等待的期间可以切换到其他任务。

另一个例子

  1. import asyncio
  2. async def others():
  3. print("start")
  4. await asyncio.sleep(2)
  5. print('end')
  6. return '返回值'
  7. async def func():
  8. print("执行协程函数内部代码")
  9. # 遇到IO操作挂起当前协程(任务),等IO操作完成之后再继续往下执行。当前协程挂起时,事件循环可以去执行其他协程(任务)。
  10. response1 = await others()
  11. print("IO请求结束,结果为:", response1)
  12. response2 = await others()
  13. print("IO请求结束,结果为:", response2)
  14. asyncio.run( func() )

cf155e1f752e40f6966b5d8d24964138.png

三、总结

使用async和await关键字可以大大简化异步编程的代码,使其更易于理解和维护。

参考:

python 异步 async/await_python await_零否的博客-CSDN博客

【python】async异步编程_python async_ynliii的博客-CSDN博客

发表评论

表情:
评论列表 (有 0 条评论,124人围观)

还没有评论,来说两句吧...

相关阅读

    相关 C# 异步编程async/await

    概述 异步这个概念在不同语境下有不同的解释,比如在一个单核CPU里开启两个线程执行两个函数,通常认为这种调用是异步的,但对于CPU来说它是单核不可能同时运行两个函数,不过