asyncio 异步io相关知识

import asyncio
#运行器
async def hello_async(delay, words):
    await asyncio.sleep(delay)
    print(words)
#协程与任务
async def test_async(): #等待第一个协程hello_async执行完以后再串行执行下一个任务,两个协程没有并发效果
    start_time = time.time()
    print('fun test_async run start_time', start_time)
    await hello_async(1, 'hello asyncio')
    await hello_async(2, 'hello asyncio')
    end_time = time.time()
    print('fun test_async run end_time %s, running time %s' % (end_time, end_time-start_time))

async def test_async1(): #asyncio.create_task实现两个异步任务并发
    start_time = time.time()
    print('fun test_async1 run start_time', start_time)
    task1 = asyncio.create_task(hello_async(1, 'hello asyncio'))
    task2 = asyncio.create_task(hello_async(2, 'hello asyncio'))
    await task1
    await task2
    end_time = time.time()
    print('fun test_async1 run end_time %s, running time %s' % (end_time, end_time-start_time))

async def test_async_tg(): #asyncio.TaskGroup()比直接使用create_task()方法更加方便,创建task一步任务后不用再await调用
    start_time = time.time()
    print('fun test_async_tg run start_time', start_time)
    async with asyncio.TaskGroup() as tg:
        task1 = tg.create_task(hello_async(1, 'hello asyncio'))
        task2 = tg.create_task(hello_async(2, 'hello asyncio'))
    end_time = time.time()
    print('fun test_async_tg run end_time %s, running time %s' % (end_time, end_time-start_time))

if __name__ == '__main__':
    asyncio.run(hello_async(1, 'hello asyncio'))
    # asyncip运行器上下文管理执行hello_async()
    with asyncio.Runner() as runner:
        runner.run(hello_async(1, 'hello asyncio'))
        runner.run(test_async())
        runner.run(test_async1())
        runner.run(test_async_tg())

 

posted @ 2024-04-03 21:11  flag_HW  阅读(14)  评论(0编辑  收藏  举报