Python 和 FastAPI 项目中的常见多线程应用
在 Python 与 FastAPI 项目中,多线程是提高性能和响应能力的重要工具。以下是一些常见的多线程应用场景和实现方式:
常见多线程应用场景
- 后台任务处理:处理耗时操作,不阻塞主请求流程
- 并行数据处理:同时处理多个数据源或大量数据
- 定时任务:周期性执行的后台任务
- 异步 I/O 操作:文件读写、网络请求等
- WebSocket 连接管理:维护多个长连接
Python 标准库中的多线程实现
import threading
import time
def background_task(name, delay):
print(f"Task {
name} started")
time.sleep(delay) # 模拟耗时操作
print(f"Task {
name} completed")
# 创建线程
t1 = threading.Thread(target=background_task, args=("A", 2))
t2 = threading.Thread(target=background_task, args=("B", 3))
# 启动线程
t1.start()
t2.start()
# 等待线程完成
t1.join()
t2.join()
print("All tasks completed")
在 FastAPI 中使用多线程
FastAPI 本身基于异步架构 (使用 Starlette 和 Uvicorn),通常不需要显式创建线程。但在某些场景下,仍然需要多线程处理:
1. 使用 BackgroundTasks 处理后台任务
from fastapi import FastAPI, BackgroundTasks
app = FastAPI()
def process_data(data: dict):
# 处理耗时任务
import time
time.sleep(5)
print(f"Processed data: {
data}")
@app.post("/submit/")
async def submit_data(data: dict, background_tasks: BackgroundTasks):
background_tasks.add_task(process_data, data)
return {
"message": "Data received, processing in background"}
2. 使用线程池处理并行任务
from fastapi import FastAPI
from concurrent.futures import ThreadPoolExecutor
import time
app = FastAPI()
executor = ThreadPoolExecutor(max_workers=5)
def cpu_bound_task(n: int):
# 模拟CPU密集型任务
result = 0
for i in range(n):
result += i
return result
@app.get("/parallel/{number}")
async def parallel_computation(number: int):
start_time = time.time()
# 将任务提交到线程池
futures = [executor.submit(cpu_bound_task, 1000000) for _ in range(number)]
results = [future.result() for future in futures]
execution_time = time.time() - start_time
return {
"execution_time": execution_time,
"thread_count": number,
"results_count": len(results)
}
3. 定期任务调度器
from fastapi import FastAPI
import threading
import time
import schedule
app = FastAPI()
def scheduled_task():
print(f"Running scheduled task at {
time.strftime('%H:%M:%S')}")
# 创建单独的线程运行调度器
def run_scheduler():
schedule.every(1).minutes.do(scheduled_task)
while True:</