我一直在尝试在我的 Jupyter 机器上测试这段简单的代码,并且单元只是无限期地运行而不输出任何内容。是否有某种错误或其他什么?我对 pandas 进程使用了完全相同的代码 pool.map
,一切都工作正常,但无法弄清楚这里发生了什么。
import multiprocessing as mp
pool1 = mp.Pool(processes = 3)
def sumP(a, b):
return (a * b) / (a - b + 1)
f1, f2, f3 = 24, 31, 45
new_rows2 = pool1.starmap(sumP, [(f1, f2), (f2, f3), (f1, f3)])
print(new_rows2)
并且单元继续运行。我使用 pool1.map
或 pool1.starmap
都没关系。
你们有建议任何其他方法来并行化这个过程吗?
最佳答案
发生这种情况是因为工作进程尝试导入 sumP
,这还会创建另外 3 个进程,无限循环。
您需要在多进程创建周围设置保护,以便工作线程不会无限期地产生:
import multiprocessing as mp
def sumP(a, b):
return (a * b) / (a - b + 1)
f1, f2, f3 = 24, 31, 45
if __name__ == "__main__":
pool1 = mp.Pool(processes=3)
new_rows2 = pool1.starmap(sumP, [(f1, f2), (f2, f3), (f1, f3)])
print(new_rows2)
在 multiprocessing docs 下查找“安全导入主模块”了解更多信息。您不应在导入主模块期间创建池。
关于python - 将函数传递给多处理池中的 map 或星图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69535321/