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

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

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

 说明:

一、使用async def 将方法变成协程,用await修饰有阻塞的操作

二、await后可跟三种类型: 协程任务 和 Future.

原文地址:https://www.cnblogs.com/staff/p/15425049.html