asyncio基础用法

说明:需要Python 3.7+

 

1、并发运行两个coroutine,写法一: 用Task

import asyncio
import time


async def say_after(delay, what):
    await asyncio.sleep(delay)
    print(what)


async def main():
    task1 = asyncio.create_task(
        say_after(1, 'hello'))

    task2 = asyncio.create_task(
        say_after(2, 'world'))

    print(f"started at {time.strftime('%X')}")

    # Wait until both tasks are completed (should take around 2 seconds.)
    r1 = await task1
    r2 = await task2
    print(f"finished at {time.strftime('%X')}")
    print("result: ", r1, r2)


asyncio.run(main())

运行时间:2s

asyncio基础用法

 

 

 

 

1、并发运行两个coroutine,写法二: 

import asyncio
import time


async def say_after(delay, what):
    await asyncio.sleep(delay)
    print(what)


async def main():
    print(f"started at {time.strftime('%X')}")

    result = await asyncio.gather(say_after(1, 'hello'), say_after(2, 'world'))

    print(f"finished at {time.strftime('%X')}")
    print("result: ", result)


asyncio.run(main())

运行时间:2s

asyncio基础用法

 

上一篇:.NET Core 之 二 异步编程 async和await


下一篇:再次理解 async/await