栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

asyncio异步编程之Task对象

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

asyncio异步编程之Task对象

1, Task对象的作用

可以将多个任务添加到事件循环当中,达到多任务并发的效果

2.如何创建task对象
asyncio.create_task(协程对象)

注意:create_task只有在python3.7及以后的版本中才可以使用,就像asyncio.run()一样,

在3.7以前可以使用asyncio.ensure_future()方式创建task对象

3.示例一(目前不推荐这种写法)
async def func():
    print(1)
    await asyncio.sleep(2)
    print(2)
    return "test"


async def main():

    print("main start")
    
    # python 3.7及以上版本的写法
    # task1 = asyncio.create_task(func())
    # task2 = asyncio.create_task(func())
    
    # python3.7以前的写法
    task1 = asyncio.ensure_future(func())
    task2 = asyncio.ensure_future(func())
    print("main end")

    ret1 = await task1
    ret2 = await task2

    print(ret1, ret2)

# python3.7以后的写法
# asyncio.run(main())

# python3.7以前的写法
loop = asyncio.get_event_loop()
loop.run_until_complete(main())

"""
在创建task的时候,就将创建好的task添加到了时间循环当中,所以说必须得有时间循环,才可以创建task,否则会报错
"""
4.示例2
async def func1():
    print(1111)
    await asyncio.sleep(2)
    print(2222)
    return "test"


async def main1():

    print("main start")

    tasks = [
        asyncio.ensure_future(func1()),
        asyncio.ensure_future(func1())
    ]

    print("main end")

    # 执行成功后结果在done中, wait中可以加第二个参数timeout,如果在超时时间内没有完成,那么pending就是未执行完的东西
    done, pending = await asyncio.wait(tasks, timeout=1)

    print(done)
    #print(pending)

# python3.7以前的写法
loop = asyncio.get_event_loop()
loop.run_until_complete(main1())
5,示例3(算是以上示例2的简化版)
"""
方式二的简化版,就是tasks中不直接添加task,而是先将协程对象加入到list中,在最后运行中添加
"""

async def func2():
    print(1111)
    await asyncio.sleep(2)
    print(2222)
    return "test"


tasks = [
    func2(),
    func2()
]

# python3.7以前的写法
loop = asyncio.get_event_loop()
done, pending = loop.run_until_complete(asyncio.wait(tasks))
print(done)
print(pending)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/757247.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号