有没有大佬懂的,为啥要有线程池

有没有大佬懂python异步编程的,为啥要有线程池,async不是协程吗,是把协程放进线程池里消费吗,不太理解,救救菜鸟
from concurrent.futures import ThreadPoolExecutor
from fastapi import FastAPI,Request,Response
import uvicorn
import asyncio
import time

创建web
app=FastAPI()

创建线程池
threadpool=ThreadPoolExecutor(max_workers=200)

@app.get('/ver2')
async def ver2(request: Request):
# 获取参数
msg=request.query_params.get('msg')

livecodeserver
复制
# 获取async io event loop
loop=asyncio.get_event_loop()

# 准备计算任务
task={
    'msg': msg,
}

# 计算函数
def handle_task():
    print('task received:',task['msg'])
    result=task['msg'].lower()
    time.sleep(2) # 模拟线程阻塞
    return result

# 提交并等待结果
result=await loop.run_in_executor(threadpool,handle_task)
return Response(result)
if name=='main':
uvicorn.run(app,host='localhost',port=8000)
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务