python-Asyncer

python-Asyncer

fastapi/asyncer: Asyncer, async and await, focused on developer experience.

使用raise_sync_error=False,如果 syncify 在 worker thread(异步的线程池上下文) 中执行,可以将异步函数从worker thread 中发送到主异步线程运行。

如果程序不是异步的,也就是不在 worker thread,那么会使用 anyio.run 重新开启一个事件循环,这个过程比较耗费资源,需要谨慎使用

import time

import anyio
from asyncer import asyncify, syncify


async def do_async_work(name: str):
    await anyio.sleep(1)
    return f"Hello, {name}"


def do_sync_work(name: str):
    time.sleep(1)
    message = syncify(do_async_work, raise_sync_error=False)(name=name)
    return message


async def main():
    message = await asyncify(do_sync_work)(name="World")
    print(message)


def sync_main():
    message = do_sync_work(name="Sync World")
    print(message)


anyio.run(main)
sync_main()