asyncio 自学笔记

2019-12-27  本文已影响0人  NanaCti

asyncio 是用来编写 并发 代码的库,使用 async/await 语法。
很好的参考

import asyncio

async def main():
     print('hello')
     await asyncio.sleep(1)
     print('world')

asyncio.run() 运行asyncio 程序

async def main():
    await asyncio.sleep(1)
    print('hello')

asyncio.run(main())

asyncio.create_task() 并发运行任务

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')}")

    # 必须加下面两行,否则不会等待任务运行完成
    await task1
    await task2

    print(f"finished at {time.strftime('%X')}")
if __name__ == '__main__':
    asyncio.run(main())

asyncio.gather() 并发运行任务

async def factorial(name, number):
    ...

async def main():
    # Schedule three calls *concurrently*:
    await asyncio.gather(
        factorial("A", 2),
        factorial("B", 3),
        factorial("C", 4),
    )

asyncio.run(main())

asyncio.shield( ) 保护一个 可等待对象 防止其被 取消。

res = await shield(something())
相当于:

res = await something()

asyncio.wait_for(aw, timeout)

等待可等待对象执行完毕,可设置超时
asyncio.wait 为等待返回值,也可设置超时

async def main():
    tasks = []
    for i in range(10):
        tasks.append(asyncio.create_task(foo()))
    await asyncio.wait(tasks)

if __name__ == '__main__':
    asyncio.run(main())
上一篇下一篇

猜你喜欢

热点阅读