【问题标题】:Wrong simple async script (python 3.5)错误的简单异步脚本(python 3.5)
【发布时间】:2018-09-26 21:37:36
【问题描述】:

我有这么简单的代码。

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/ 中打开我的浏览器时,我看到了“开始”的文字,然后在大约 10 秒后我看到了“停止”的文字。然后我同时打开两个页面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

我做错了什么?

【问题讨论】:

    标签: python-3.x python-asyncio aiohttp pytest-aiohttp


    【解决方案1】:

    您有一个受 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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-05
      • 1970-01-01
      • 2017-07-24
      • 2016-05-12
      • 2017-02-13
      • 2012-11-13
      相关资源
      最近更新 更多