温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

asyncio异步编程中Task对象是什么

发布时间:2022-03-14 09:21:50 来源:亿速云 阅读:141 作者:小新 栏目:开发技术

小编给大家分享一下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)

以上是“asyncio异步编程中Task对象是什么”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI