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

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

asyncio異步編程之Task對(duì)象詳解_python

作者:一起學(xué)python吧 ? 更新時(shí)間: 2022-05-15 編程語(yǔ)言

1.Task對(duì)象的作用

可以將多個(gè)任務(wù)添加到事件循環(huán)當(dāng)中,達(dá)到多任務(wù)并發(fā)的效果

2.如何創(chuàng)建task對(duì)象

asyncio.create_task(協(xié)程對(duì)象)

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

在3.7以前可以使用asyncio.ensure_future()方式創(chuàng)建task對(duì)象

3.示例一(目前不推薦這種寫(xiě)法)

async def func():
    print(1)
    await asyncio.sleep(2)
    print(2)
    return "test"
async def main():
    print("main start")
    # python 3.7及以上版本的寫(xiě)法
    # task1 = asyncio.create_task(func())
    # task2 = asyncio.create_task(func())
    # python3.7以前的寫(xiě)法
    task1 = asyncio.ensure_future(func())
    task2 = asyncio.ensure_future(func())
    print("main end")
    ret1 = await task1
    ret2 = await task2
    print(ret1, ret2)
# python3.7以后的寫(xiě)法
# asyncio.run(main())
# python3.7以前的寫(xiě)法
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
"""
在創(chuàng)建task的時(shí)候,就將創(chuàng)建好的task添加到了時(shí)間循環(huán)當(dāng)中,所以說(shuō)必須得有時(shí)間循環(huán),才可以創(chuàng)建task,否則會(huì)報(bào)錯(cuò)
"""

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")
    # 執(zhí)行成功后結(jié)果在done中, wait中可以加第二個(gè)參數(shù)timeout,如果在超時(shí)時(shí)間內(nèi)沒(méi)有完成,那么pending就是未執(zhí)行完的東西
    done, pending = await asyncio.wait(tasks, timeout=1)
    print(done)
    #print(pending)
# python3.7以前的寫(xiě)法
loop = asyncio.get_event_loop()
loop.run_until_complete(main1())

5.示例3(算是以上示例2的簡(jiǎn)化版)

"""
方式二的簡(jiǎn)化版,就是tasks中不直接添加task,而是先將協(xié)程對(duì)象加入到list中,在最后運(yùn)行中添加
"""
async def func2():
    print(1111)
    await asyncio.sleep(2)
    print(2222)
    return "test"
tasks = [
    func2(),
    func2()
]
# python3.7以前的寫(xiě)法
loop = asyncio.get_event_loop()
done, pending = loop.run_until_complete(asyncio.wait(tasks))
print(done)
print(pending)

總結(jié)

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

欄目分類(lèi)
最近更新