FastAPI 中的 `run_in_executor` 和 `run_in_threadpool` 有什么区别?

Lor*_*zoC 6 python python-3.x python-asyncio fastapi

在FastAPI中,run_in_executor两者run_in_threadpool都可以让函数在其他线程中运行,并且似乎具有相同的行为

但这有什么区别呢?使用 FastAPI 的最佳选择是什么?

演示:

import asyncio
import time
from fastapi import FastAPI
from fastapi.concurrency import run_in_threadpool

app = FastAPI()


@app.get("/")
async def index():
    result = await long_time_work()
    result = await long_time_work2()
    return {"message": result}


async def long_time_work():
    loop = asyncio.get_event_loop()
    await loop.run_in_executor(None, time.sleep, 5)
    return True


async def long_time_work2():
    await run_in_threadpool(lambda: time.sleep(5))
    return True

Run Code Online (Sandbox Code Playgroud)

Mah*_*ghi 1

run_in_threadpoolanyio.to_thread.run_sync正在幕后使用。这使得它可以根据环境(asyncio 或 trio)与不同的异步后端配合使用。

它们都在线程池中运行同步方法,但run_in_executor为用户提供了更多控制权,例如选择不同的执行器。这将允许您在与默认线程池分开的特定线程池中运行同步方法,限制并发线程的数量,甚至传递进程执行器实例以在单独的进程中运行它们。