我有一个如此简单的代码。
from aiohttp import web
async def hello(request):
print('Start')
for el in range(30000000):
# Any expression
1+el/10000*100000-4*234
print('Stop')
return web.Response(text="Hello, world")
app = web.Application()
app.add_routes([web.get('/', hello)])
web.run_app(app)当我在http://0.0.0.0:8080/中打开我的浏览器时,我得到了文本"Start",然后大约10秒后,我得到了文本"Stop“。然后我同时打开两个页面的http://0.0.0.0:8080/。我希望在10-11秒内收到这样的短信
'Start' #right now
'Start' #right now
'Stop' #in 10 sec
'Stop' #next sec但我得到(在21秒内)
'Start' #right now
'Stop' #in 10 sec
'Start' #at 11th sec
'Stop' #at 22th sec我做错了什么?
发布于 2018-09-27 20:54:15
你有一个CPU绑定的代码:
for el in range(30000000):
# Any expression
1+el/10000*100000-4*234它会阻止事件循环的执行。
要解决此问题,请将这些代码移动到线程池执行器中。
修复后的示例:
import asyncio
from aiohttp import web
def long_running_cpu_bound_task():
for el in range(30000000):
# Any expression
1+el/10000*100000-4*234
async def hello(request):
print('Start')
await asyncio.get_event_loop().run_in_executor(
None,
long_running_cpu_bound_task)
print('Stop')
return web.Response(text="Hello, world")
app = web.Application()
app.add_routes([web.get('/', hello)])
web.run_app(app)https://stackoverflow.com/questions/52526347
复制相似问题