运行 循环的每次迭代中的函数作为 python 中的新进程

Running a function in each iteration of a loop as a new process in python

我有这个:

from multiprocessing import Pool

pool = Pool(processes=4)

def createResults(uniqPath):
    *(there is some code here that populates a list - among other things)*

for uniqPath in uniqPaths:
    pool.map(createResults, uniqPath)

pool.close()
pool.join()

我不知道这是否可行,但我可以 运行 在该循环中调用的 createResults 函数作为每次迭代的新进程吗?

我正在使用一个 400 万行的文件填充一个列表,运行 需要 24 多个小时。 (显然上面的代码不起作用)

谢谢!

而不是:

for uniqPath in uniqPaths:
    pool.map(createResults, uniqPath)

这样做:

pool.map(createResults, uniqPaths)

您必须在可迭代本身上使用 map 以便 运行 以并发方式进行。
但请记住 - 填充列表意味着该列表不会在进程之间共享,如果确实使用 Array(),请确保它是进程安全的。