python asyncio

家电维修 2022-11-07 12:21www.17kangjie.cn家电维修培训

python协程库asyncio的运行方式有哪些?我们一起了解一下吧!

asyncio 是以协程的模式来编写并发的库,使用 async/aait 语法。在 IO密集型 的网络编程里,异步IO 协程 省去了开辟新的线程和进程的开销。asyncio 是 Python3.4 版本引入到标准库,python3.5 加入了 async/aait 特性。下面长沙家政网我们就来分享一下运行协程的几种方式。

使用 async 声明协程

async def asyncTask():

    # 协程休眠

    aait asyncio.sleep(1)

    print(time.strftime('%X'))

运行协程的几种方式:

1、asyncio.run() 函数用来在非协程函数中调用协程

asyncio.run(asyncTask())

2、使用 aait 等待一个协程。

aait asyncTask()

3、asyncio.create_task() 用函数将协程打包为一个 Task 排入日程准备执行,返回 asyncio.Task 对象。

此函数 在 Python 3.7 中被加入。

task1 = asyncio.create_task(asyncTask1())task2 = asyncio.create_task(asyncTask2())aait task1aait task2

4、使用 asyncio.gather() 函数来并发多个协程。

tasks = asyncio.gather(asyncTask1(), asyncTask2())tasks2 = asyncio.gather(*[asyncTask1(), asyncTask2()])aait tasksaait tasks2

具体示例:

import asyncioimport time# 定义协程任务async def asyncTask1():

    # 协程休眠

    aait asyncio.sleep(1)

    print(time.strftime('%X'), 1)async def asyncTask2():

    aait 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()])    aait tasks    aait tasks2    aait task1    aait task2

print(time.strftime('%X'), "start")

asyncio.run(main())

print(time.strftime('%X'), "end")

关于运行协程的方式,我们就了解到这啦!

上一篇:es6数组去重 下一篇:lte关闭还是开启好

Copyright © 2016-2025 www.17kangjie.cn 长沙家政网【一起康洁家政】 版权所有 Power by