Python 官方文档:入门教程 => 点击学习
目录1.Task对象的作用2.如何创建task对象3.示例一(目前不推荐这种写法)4.示例25.示例3(算是以上示例2的简化版)总结1.Task对象的作用 可以将多个任务添加到事件循
可以将多个任务添加到事件循环当中,达到多任务并发的效果
asyncio.create_task(协程对象)
注意:create_task
只有在python3.7及以后的版本中才可以使用,就像asyncio.run()
一样,
在3.7以前可以使用asyncio.ensure_future()
方式创建task对象
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,否则会报错
"""
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())
"""
方式二的简化版,就是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)
本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注编程网的更多内容!
--结束END--
本文标题: asyncio异步编程之Task对象详解
本文链接: https://www.lsjlt.com/news/142231.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0