2019-01-12更新
我重新安装了Python 3.7.1,并重新制作了venv,以恢复一切。
但是,我仍然不知道3.7.2中会发生什么。
我在数据处理项目中一直在使用 multiprocessing.map_async 和.apply_async。在python 3.6到3.7.1之前,它都可以正常工作,但是当我升级到3.7.2并重新创建venv时,主进程无限期地挂起,子进程根本无法工作。
我正在使用 Windows10 和PyCharm社区。
我尝试了PyCharm中的工具和python -m venv来创建venv,但是都没有。
我在python.org中寻找文档,发现
https://docs.python.org/3.7/whatsnew/changelog.html#python-3-7-2-final
它说,
"venv on Windows will now use a python.exe redirector rather than copying the actual binaries from the base environment."
我想知道这是否引起了问题。
示例代码如下:
from multiprocessing import freeze_support, Pool
def test_func(x):
y = x + 1
return y
if __name__ == '__main__':
freeze_support()
test_data = list(range(10))
with Pool(4) as test_pool:
for test_datum in test_data:
apply_result = test_pool.apply_async(test_func, test_datum)
print(apply_result.get())
我在最后一行添加一个断点,然后进入 Debug模式。然后,我发现 apply_result 对象(即 multiprocessing.pool.ApplyResult )具有 _cache 属性。在 _cache 下,有一个相同的 multiprocessing.pool.ApplyResult ,但名称为“ 0(140716767896368)”,它还具有一个 _cache 属性,并不断打开。
debug
我很拼命,尝试了最简单的代码(从官方文档修改):
from multiprocessing import Pool, freeze_support
def f(x):
return x*x
if __name__ == '__main__':
freeze_support()
p = Pool(5)
print(p.map(f, [1, 2, 3]))
它仍然挂着。
如果我选择系统解释器,而不使用venv,则可以正常工作。
[1, 4, 9]
衷心感谢您为解决这个问题所提供的帮助。
最佳答案
在Mac和VS Code上,我遇到了同样的问题。
所以这是我的解决方案。
import joblib
from joblib import Parallel,delayed
def f(x):
return x*x
number_of_cpu = joblib.cpu_count()
delayed_funcs = [delayed(f)(x) for x in [1,2,3]]
parallel_pool = Parallel(n_jobs=number_of_cpu,prefer="processes")
print(parallel_pool(delayed_funcs))
无论如何,该文档有据可查...
关于python - 如何使用venv解决Python 3.7.2中的多处理停止工作问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54151041/