有没有大佬懂的,为啥要有线程池
有没有大佬懂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)
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)
全部评论
相关推荐
05-07 21:46
门头沟学院 电子信息类 点赞 评论 收藏
转发
投递腾讯等公司7个岗位
点赞 评论 收藏
转发
点赞 评论 收藏
转发