Here is an example using a list of integers.
This code just breaks up an array of 1000 integers from 0, 1, 2, ... 999 into chunk sizes of 10 ending up with 1000 / 10 = 100 chunks and creates 100 lists from these chunks. These chunks along with its starting index are submitted to a worker that sums the elements of the lists and returns back the starting index and sum, which is then used to compute the grand total. Here the starting index is not being used to calculate the grand total but in another context it could be useful.
from multiprocessing import Pool, Array
import itertools
def init_pool(arr):
global data
data = arr
def my_worker(tpl):
index, results_chunk = tpl
# sum items from results_chunk and data array:
data_index = index
the_sum = 0
for item in results_chunk:
the_sum += item + data[data_index]
data_index += 1
return index, the_sum
def get_chunks(arr, size):
index = 0
it = iter(arr)
while True:
x = tuple(itertools.islice(it, size))
if not x:
return
yield index, list(x)
index += size
# required for Windows and other platforms that do not have a fork() call:
if __name__ == '__main__':
data = [x for x in range(1000, 2000)]
data_sum = sum(data)
arr = Array('i', data, lock=False)
results = [x for x in range(1000)]
results_sum = sum(results)
print('Excpected total sum =', data_sum + results_sum)
with Pool(initializer=init_pool, initargs=(arr,)) as pool:
total = 0
for index, the_sum in pool.imap_unordered(my_worker, get_chunks(results, 10), 3):
total += the_sum
print('Actual total sum =', total)
Prints:
Excpected total sum = 1999000
Actual total sum = 1999000
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…