简体   繁体   English

从异步函数调用同步函数

[英]calling sync functions from async function

I am in the process of trying to port a flask app to quart to utilise asyncio .我在试图端口的过程flask应用quart利用asyncio I don't think my current approach is working, as my entire function chain is written without async in mind - consider the following:我认为我目前的方法行不通,因为我的整个函数链是在没有考虑异步的情况下编写的 - 考虑以下几点:

def long_running_task(task):
    result = some_synchronous_function(task)
    return result

@app.route('/<task>', methods=['GET'])
async def do_task(task):
    ok = await long_running_task(task)
    if ok:
        return (ok.result)
    else:
        return ('Something went wrong')

If long_running_task and its whole chain of function calls are not declared as async , am I actually getting any benefit from my route being declared as async ?如果long_running_task及其整个函数调用链未声明为async ,我实际上是否从我的路由声明为async获得任何好处?

To run a blocking synchronous function from asyncio, without blocking the main event loop, you can use loop.run_in_executor() to run the blocking function in a ThreadPoolExecutor or ProcessPoolExecutor ` (ie in its own thread or process).要从 asyncio 运行阻塞同步函数,而不阻塞主事件循环,您可以使用loop.run_in_executor()ThreadPoolExecutorProcessPoolExecutor `(即在其自己的线程或进程中)运行阻塞函数。

From within the async function you want to call it from:从你想要调用它的异步函数中:

loop = asyncio.get_event_loop()

result = await loop.run_in_executor(None, long_running_task, task)

The first argument None is to tell it to use the default executor for the loop.第一个参数None是告诉它使用循环的默认执行器。 Obviously do_task() will still have to wait for result to complete, but while it is waiting, other async tasks will be able to run in event-loop.显然do_task()仍然需要等待result完成,但在等待期间,其他异步任务将能够在事件循环中运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM