我很纠结这个问题。
我有一大串列表,我想用并行代码访问这些列表以执行 CPU 密集型操作。为了做到这一点,我正在尝试使用multiprocessing.Pool
,问题是我还需要在我的子进程中查看这个庞大的列表列表。
由于“列表列表”不是常规的(例如:),因此我[[1, 2], [1, 2, 3]]
无法将它们存储为mp.Array
,并且如前所述,我没有使用mp.Process
,所以我没有想出mp.Manager
在此任务中使用的方法。保留这个列表列表对我来说很重要,因为我正在应用一个基于索引进行查询的函数,使用from operator import itemgetter
.
这是我想要实现的一个虚构示例:
import multiprocessing as mp
from operator import itemgetter
import numpy as np
def foo(indexes):
# here I must guarantee read acess for big_list_of_lists on every child process somehow
# as this code would work with only with one child process using global variables but would fail
# with larger data.
store_tuples = itemgetter(*indexes)(big_list_of_lists)
return np.mean([item for sublista in store_tuples for item in sublista])
def main():
# big_list_of_lists is the varible that I want to share across my child process
big_list_of_lists = [[1, 3], [3, 1, 3], [1, 2], [2, 0]]
ctx = mp.get_context('spawn')
# big_list_of_lists elements are also passed as args
pool = mp.Pool(ctx.Semaphore(mp.cpu_count()).get_value())
res=list(pool.map(foo, big_list_of_lists))
pool.close()
pool.join()
return res
if __name__ is '__main__':
print(main())
# desired output is equivalente to:
# a = []
# for i in big_list_of_lists:
# store_tuples = itemgetter(*i)(big_list_of_lists)
# a.append(np.mean([item for sublista in store_tuples for item in sublista]))
# 'a' would be equal to [1.8, 1.5714285714285714, 2.0, 1.75]
其他细节:最好使用 python 3.6 实现解决方案,并且必须在 Windows 上工作
非常感谢你!