【发布时间】:2022-12-21 00:37:47
【问题描述】:
我正在尝试使用 ProcessPoolExecutor 异步运行阻塞任务(它与 ThreadPoolExecutor 一起使用,但我需要 ProcessPoolExecutor 来执行 CPU 绑定任务)。这是我的代码:
import asyncio
import time
from concurrent.futures import ProcessPoolExecutor
async def run_in_thread(task, *args):
with ProcessPoolExecutor() as process_pool:
loop = asyncio.get_event_loop()
result = await loop.run_in_executor(process_pool, task, *args)
return result
async def main_task():
while True:
await asyncio.sleep(1)
print("ticker")
async def main():
asyncio.create_task(main_task())
global blocking_task
def blocking_task():
time.sleep(5)
print("blocking task done!")
await run_in_thread(blocking_task)
if __name__ == "__main__":
asyncio.run(main())
我得到这个错误:
result = await loop.run_in_executor(process_pool, task, *args)
concurrent.futures.process.BrokenProcessPool: A process in the process pool was terminated abruptly while the future was running or pending.
我不明白问题出在哪里,有人可以帮助我吗? 我还想了解为什么它适用于 ThreadPoolExecutor 而不是 ProcessPoolExecutor
我期待代码打印:
ticker
ticker
ticker
ticker
ticker
blocking task done!
【问题讨论】:
标签: python multithreading asynchronous multiprocessing python-asyncio