日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

asyncio異步編程之Task對象詳解_python

作者:一起學python吧 ? 更新時間: 2022-05-15 編程語言

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)

總結

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

欄目分類
最近更新