多处理 AsyncResult.get() 在 Python 3.7.2 中挂起,但在 3.6 中没有

问题描述

我正在尝试将一些代码从 Python 3.6 移植到 Windows 10 上的 Python 3.7.在 AsyncResult 上调用 .get() 时,我看到多处理代码挂起目的.有问题的代码要复杂得多,但我已将其归结为类似于以下程序的代码.

I'm trying to port some code from Python 3.6 to Python 3.7 on Windows 10. I see the multiprocessing code hang when calling .get() on the AsyncResult object. The code in question is much more complicated, but I've boiled it down to something similar to the following program.

import multiprocessing


def main(num_jobs):
    num_processes = max(multiprocessing.cpu_count() - 1, 1)
    pool = multiprocessing.Pool(num_processes)

    func_args = []
    results = []

    try:
        for num in range(num_jobs):
            args = (1, 2, 3)
            func_args.append(args)
            results.append(pool.apply_async(print, args))

        for result, args in zip(results, func_args):
            print('waiting on', args)
            result.get()
    finally:
        pool.terminate()
        pool.join()


if __name__ == '__main__':
    main(5)

此代码也在 Python 2.7 中运行.出于某种原因,对 get() 的第一次调用在 3.7 中挂起,但在其他版本上一切正常.

This code also runs in Python 2.7. For some reason the first call to get() hangs in 3.7, but everything works as expected on other versions.


解决方案

我认为这是 Python 3.7.2 中描述的回归 这里.它似乎只在 virtualenv 中运行时影响用户.

I think this is a regression in Python 3.7.2 as described here. It seems to only affect users when running in a virtualenv.

暂时您可以通过执行在此错误线程的评论中描述的操作来解决它.

import _winapi
import multiprocessing.spawn
multiprocessing.spawn.set_executable(_winapi.GetModuleFileName(0))

这将强制子进程使用 real python.exe 而不是 virtualenv 中的那个生成.因此,如果您使用 PyInstaller 将内容捆绑到 exe 中,这可能不合适,但在使用本地 Python 安装从 CLI 运行时,它可以正常工作.

That will force the subprocesses to spawn using the real python.exe instead of the one that's in the virtualenv. So, this may not be suitable if you're bundling things into an exe with PyInstaller, but it works OK when running from the CLI with local Python installation.

相关文章