最好使用多处理池进行细微的循环?

时间:2019-06-19 23:00:12

标签: python multithreading multiprocessing

我正在尝试找出利用python的多处理Pool的最佳方法。

我有一个n ^ 2嵌套的for循环,可以对存储桶列表中的每个存储桶组合进行比较。

我想使用多处理Pool进行并行处理的工作是compare()函数调用。

compare函数中绝对没有共享资源。如果存储桶A和B正在比较,而存储桶A和C正在通过另一个过程,则没关系。

我是并行处理的新手,但我确实了解多处理Pool的基本性质。但是,我发现很难实现我想做的任何事情。

当我查看reader_list的任何示例时,对特定存储区对以及与之关联的Pool的依赖似乎使我受阻。我不一定要依赖该函数在每个索引上执行的列表。

for i in range(0, len(bucket_names) - 1):
    bucket1 = bucket_names[i]

    for k in range(i+1, len(bucket_names)):
        bucket2 = bucket_names[k]

        reader_list1 = get_reader_list(bucket1)
        reader_list2 = get_reader_list(bucket2)

        compare(bucket1, bucket2, reader_list1, reader_list2)

1 个答案:

答案 0 :(得分:1)

您的意思是您需要一个如何使用Pool并行化功能的示例吗?这是一个例子。

import multiprocessing as mp

# Generate your arguments as a list of tuples, using some method that fits your requirements. 
# Here is a hard-coded example
arguments = [(bucket1, bucket2), (bucket2, bucket3), (bucket1, bucket3)]

# Create pool given number of logical CPUs you have
pool = mp.Pool(mp.cpu_count())

# Assign work to pool (provide function and list of arguments)
# Results will be list of results
results = pool.starmap(compare, arguments)