【发布时间】:2019-05-06 18:26:02
【问题描述】:
我的问题与Combining asyncio with a multi-worker ProcessPoolExecutor 非常相似-但是稍有变化(我相信是async for)使那里的出色答案对我来说无法使用。
我正在尝试以下 MWE:
import concurrent.futures
import asyncio
import time
async def mygen(u: int = 2):
i = 0
while i < u:
yield i
i += 1
def blocking(delay):
time.sleep(delay+1)
return('EXECUTOR: Completed blocking task number ' + str(delay+1))
async def non_blocking(loop):
with concurrent.futures.ProcessPoolExecutor() as executor:
async for i in mygen():
print('MASTER: Sending to executor blocking task number ' + str(i+1))
result = await loop.run_in_executor(executor, blocking, i)
print(result)
print('MASTER: Well done executor - you seem to have completed blocking task number ' + str(i+1))
loop = asyncio.get_event_loop()
loop.run_until_complete(non_blocking(loop))
正如预期的那样,由此产生的输出不是异步的:
MASTER: Sending to executor blocking task number 1
EXECUTOR: Completed blocking task number 1
MASTER: Well done executor - you seem to have completed blocking task number 1
MASTER: Sending to executor blocking task number 2
EXECUTOR: Completed blocking task number 2
MASTER: Well done executor - you seem to have completed blocking task number 2
我想调整代码,使任务在两个并发进程中运行,并在输出可用时打印输出。期望的输出是:
MASTER: Sending to executor blocking task number 1
MASTER: Sending to executor blocking task number 2
EXECUTOR: Completed blocking task number 1
MASTER: Well done executor - you seem to have completed blocking task number 1
EXECUTOR: Completed blocking task number 2
MASTER: Well done executor - you seem to have completed blocking task number 2
我从Combining asyncio with a multi-worker ProcessPoolExecutor 了解到,就目前情况而言,我的await loop.run_in_executor() 语法是阻塞的。我不知道如何以允许async for 在等待执行者完成工作时移动到下一个生成值的方式替换它。注意我没有像他们的例子那样使用asyncio.gather。
【问题讨论】:
标签: python python-asyncio concurrent.futures