![](/img/trans.png)
[英]How to run a blocking task asynchronously with ProcessPoolExecutor and asyncio?
[英]AsyncIO run in executor using ProcessPoolExecutor
我尝试使用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
块中启动,并且永远不会返回控制权。 怎么会这样 在多处理执行程序中,将常规协程和期货结合起来的正确方法是什么?
这行:
future = loop.run_in_executor(executor, run(blocking))
实际上将运行阻塞函数并将其结果提供给执行程序。
根据文档 ,您需要显式传递该函数及其后的参数。
future = loop.run_in_executor(executor, run, blocking)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.