zoukankan      html  css  js  c++  java
  • Python 协程库 asyncio 的简单理解和使用

    基本概念:
    asyncio 是以协程的模式来编写并发的库,使用 async/await 语法。
    在 IO密集型 的网络编程里,异步IO 协程 省去了开辟新的线程和进程的开销。
    asyncio 是 Python3.4 版本引入到标准库,python3.5 加入了 async/await 特性。

    使用 async 声明协程

    async def asyncTask():
        # 协程休眠
        await asyncio.sleep(1)
        print(time.strftime('%X'))
    

    运行协程的几种方式:

    • asyncio.run() 函数用来在非协程函数中调用协程
    asyncio.run(asyncTask())
    
    • 使用 await 等待一个协程。
    await asyncTask()
    
    • asyncio.create_task() 用函数将协程打包为一个 Task 排入日程准备执行,返回 asyncio.Task 对象。
      此函数 在 Python 3.7 中被加入。
    task1 = asyncio.create_task(asyncTask1())
    task2 = asyncio.create_task(asyncTask2())
    await task1
    await task2
    
    • 可以使用 asyncio.gather() 函数来并发多个协程。
    tasks = asyncio.gather(asyncTask1(), asyncTask2())
    tasks2 = asyncio.gather(*[asyncTask1(), asyncTask2()])
    await tasks
    await tasks2
    

    整体示例:

    import asyncio
    import time
    
    
    # 定义协程任务
    async def asyncTask1():
        # 协程休眠
        await asyncio.sleep(1)
        print(time.strftime('%X'), 1)
    
    
    async def asyncTask2():
        await asyncio.sleep(2)
        print(time.strftime('%X'), 2)
    
    
    async def main():
        task1 = asyncio.create_task(asyncTask1())
        task2 = asyncio.create_task(asyncTask2())
        tasks = asyncio.gather(asyncTask1(), asyncTask2())
        tasks2 = asyncio.gather(*[asyncTask1(), asyncTask2()])
        await tasks
        await tasks2
        await task1
        await task2
    
    print(time.strftime('%X'), "start")
    asyncio.run(main())
    print(time.strftime('%X'), "end")
    

    输出:

  • 相关阅读:
    AC自动机
    HDU
    2020牛客寒假算法基础集训营3 B 牛牛的DRB迷宫II
    POJ 3784 Running Median【维护动态中位数】
    CodeForces
    HDU 2444 The Accomodation of Students【二分图最大匹配问题】
    POJ 1201 Intervals【差分约束】
    POJ 2976 Dropping tests【0/1分数规划模板】
    2019牛客暑期多校训练营(第七场)A.String【最小表示法】
    POJ 1287 Networking【kruskal模板题】
  • 原文地址:https://www.cnblogs.com/congxinglong/p/13589959.html
Copyright © 2011-2022 走看看