脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - asyncio异步编程之Task对象详解

asyncio异步编程之Task对象详解

2022-11-01 11:33一起学python吧 Python

这篇文章主要为大家详细介绍了asyncio异步编程之Task对象,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助

1.Task对象的作用

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

2.如何创建task对象

?
1
asyncio.create_task(协程对象)

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

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

3.示例一(目前不推荐这种写法)

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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的简化版)

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
"""
方式二的简化版,就是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)

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注服务器之家的更多内容!   

原文链接:https://blog.csdn.net/myli_binbin/article/details/123380985

延伸 · 阅读

精彩推荐