[英]Python 3.5 async for blocks the ioloop
我有一个简单的aiohttp服务器,有两个处理程序。 第一个在async for
循环中进行一些计算。 第二个只返回文本响应。 not_so_long_operation
以最慢的递归实现返回第30个斐波纳契数,这需要大约一秒钟。
def not_so_long_operation():
return fib(30)
class arange:
def __init__(self, n):
self.n = n
self.i = 0
async def __aiter__(self):
return self
async def __anext__(self):
i = self.i
self.i += 1
if self.i <= self.n:
return i
else:
raise StopAsyncIteration
# GET /
async def index(request):
print('request!')
l = []
async for i in arange(20):
print(i)
l.append(not_so_long_operation())
return aiohttp.web.Response(text='%d\n' % l[0])
# GET /lol/
async def lol(request):
print('request!')
return aiohttp.web.Response(text='just respond\n')
当我尝试获取/
然后/lol/
,只有当第一个完成时,它才会给出第二个响应。
我做错了什么以及如何使索引处理程序在每次迭代时释放ioloop?
您的示例没有用于在任务之间切换的屈服点 ( await
语句)。 异步迭代器允许在__aiter__
/ __anext__
使用await
但不要将其自动插入到代码中。
说,
class arange:
def __init__(self, n):
self.n = n
self.i = 0
async def __aiter__(self):
return self
async def __anext__(self):
i = self.i
self.i += 1
if self.i <= self.n:
await asyncio.sleep(0) # insert yield point
return i
else:
raise StopAsyncIteration
应该像你期望的那样工作。
在实际应用程序中,您很可能不需要await asyncio.sleep(0)
调用,因为您将等待数据库访问和类似活动。
因为, fib(30)
是CPU绑定的并且共享很少的数据,所以你应该使用ProcessPoolExecutor
(而不是ThreadPoolExecutor
):
async def index(request):
loop = request.app.loop
executor = request.app["executor"]
result = await loop.run_in_executor(executor, fib, 30)
return web.Response(text="%d" % result)
创建app
时设置executor
app
:
app = Application(...)
app["exector"] = ProcessPoolExector()
这里不需要异步迭代器。 相反,您可以简单地将控件返回到循环内的事件循环。 在python 3.4中,这是通过使用简单的yield
来完成的:
@asyncio.coroutine
def index(self):
for i in range(20):
not_so_long_operation()
yield
在python 3.5中,您可以定义一个基本上执行相同操作的Empty
对象:
class Empty:
def __await__(self):
yield
然后使用await
语法:
async def index(request):
for i in range(20):
not_so_long_operation()
await Empty()
或者只使用最近优化的 asyncio.sleep(0) :
async def index(request):
for i in range(20):
not_so_long_operation()
await asyncio.sleep(0)
您还可以使用默认执行 not_so_long_operation
在线程中运行not_so_long_operation
:
async def index(request, loop):
for i in range(20):
await loop.run_in_executor(None, not_so_long_operation)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.