How can I wrap a synchronous function in an async coroutine?

后端 未结 4 561
南笙
南笙 2021-01-30 08:28

I\'m using aiohttp to build an API server that sends TCP requests off to a seperate server. The module that sends the TCP requests is synchronous and a black box for my purposes

4条回答
  •  故里飘歌
    2021-01-30 09:09

    Not sure if too late but you can also use a decorator to do your function in a thread. ALTHOUGH, note that it will still be non-coop blocking unlike async which is co-op blocking.

    def wrap(func):
        from concurrent.futures import ThreadPoolExecutor
        pool=ThreadPoolExecutor()
        @wraps(func)
        async def run(*args, loop=None, executor=None, **kwargs):
            if loop is None:
                loop = asyncio.get_event_loop()
            future=pool.submit(func, *args, **kwargs)
            return asyncio.wrap_future(future)
        return run
    

提交回复
热议问题