我尝试使用ProcessPoolExecutor
将阻塞任务和非阻塞(I / O绑定)任务结合起来,发现它的行为非常意外。
class BlockingQueueListener(BaseBlockingListener):
def run(self):
# Continioulsy listening a queue
blocking_listen()
class NonBlockingListener(BaseNonBlocking):
def non_blocking_listen(self):
while True:
await self.get_message()
def run(blocking):
blocking.run()
if __name__ == "__main__":
loop = asyncio.get_event_loop()
executor = ProcessPoolExecutor()
blocking = BlockingQueueListener()
non_blocking = NonBlockingListener()
future = loop.run_in_executor(executor, run(blocking))
loop.run_until_complete(
asyncio.gather(
non_blocking.main(),
future
)
)
我原本期望两个任务同时具有控制权,但阻止任务在ProcessPoolExecutor
块中开始,永远不会返回控制。怎么会发生?在多处理执行器中开始组合正常协同程序和期货的正确方法是什么?
答案 0 :(得分:2)
这一行:
future = loop.run_in_executor(executor, run(blocking))
实际上会运行阻塞函数并将其结果提供给执行程序。
根据documentation,你需要明确地传递函数,然后传递它的参数。
future = loop.run_in_executor(executor, run, blocking)