Как использовать multiprocessing для решения проблемы embarrassingly parallel problems?Решение проблем с параллельными задачами с использованием многопроцессорной обработки Python
чрезвычайная параллельности проблема, как правило, состоит из трех основных частей:
- Чтение входных данных (из файла, баз данных, соединение TCP и т.д.).
- Выполнение расчетов по входным данным, где каждый расчет равен независимо от каких-либо других расчетов.
- Напишите результаты расчетов (в файл, базу данных, подключение к tcp и т. Д.).
Мы можем распараллелить программу в двух измерениях:
- Часть 2 может работать на нескольких ядрах, поскольку каждый расчет не зависит; порядок обработки не имеет значения.
- Каждая часть может работать независимо. Часть 1 может помещать данные в очередь ввода, часть 2 может вытащить данные из входной очереди и поместить результаты в очередь вывода, а часть 3 может вывести результаты из очереди вывода и записать их.
Это кажется наиболее базовой модели в параллельном программировании, но я все еще потеряно в попытке решить, так давайте напишем канонический пример, чтобы проиллюстрировать, как это делается с помощью многопроцессорных.
Вот пример проблемы: Учитывая CSV file с целыми числами в качестве входных данных, вычислите их суммы. Отдельные проблемы на три части, которые все могут работать параллельно:
- обработать входной файл в исходные данные (списки/итерируемых целых числа)
- вычислить суммы данных, параллельно
- Выхода суммы
Ниже традиционная однопроцессные связанная программу Python, который решает эти три задачи:
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# basicsums.py
"""A program that reads integer values from a CSV file and writes out their
sums to another CSV file.
"""
import csv
import optparse
import sys
def make_cli_parser():
"""Make the command line interface parser."""
usage = "\n\n".join(["python %prog INPUT_CSV OUTPUT_CSV",
__doc__,
"""
ARGUMENTS:
INPUT_CSV: an input CSV file with rows of numbers
OUTPUT_CSV: an output file that will contain the sums\
"""])
cli_parser = optparse.OptionParser(usage)
return cli_parser
def parse_input_csv(csvfile):
"""Parses the input CSV and yields tuples with the index of the row
as the first element, and the integers of the row as the second
element.
The index is zero-index based.
:Parameters:
- `csvfile`: a `csv.reader` instance
"""
for i, row in enumerate(csvfile):
row = [int(entry) for entry in row]
yield i, row
def sum_rows(rows):
"""Yields a tuple with the index of each input list of integers
as the first element, and the sum of the list of integers as the
second element.
The index is zero-index based.
:Parameters:
- `rows`: an iterable of tuples, with the index of the original row
as the first element, and a list of integers as the second element
"""
for i, row in rows:
yield i, sum(row)
def write_results(csvfile, results):
"""Writes a series of results to an outfile, where the first column
is the index of the original row of data, and the second column is
the result of the calculation.
The index is zero-index based.
:Parameters:
- `csvfile`: a `csv.writer` instance to which to write results
- `results`: an iterable of tuples, with the index (zero-based) of
the original row as the first element, and the calculated result
from that row as the second element
"""
for result_row in results:
csvfile.writerow(result_row)
def main(argv):
cli_parser = make_cli_parser()
opts, args = cli_parser.parse_args(argv)
if len(args) != 2:
cli_parser.error("Please provide an input file and output file.")
infile = open(args[0])
in_csvfile = csv.reader(infile)
outfile = open(args[1], 'w')
out_csvfile = csv.writer(outfile)
# gets an iterable of rows that's not yet evaluated
input_rows = parse_input_csv(in_csvfile)
# sends the rows iterable to sum_rows() for results iterable, but
# still not evaluated
result_rows = sum_rows(input_rows)
# finally evaluation takes place as a chain in write_results()
write_results(out_csvfile, result_rows)
infile.close()
outfile.close()
if __name__ == '__main__':
main(sys.argv[1:])
Давайте возьмем эту программу и перепишем ее для использования многопроцессорности, чтобы распараллелить три части, описанные выше. Ниже представлена структура этого нового, распараллелить программу, которая должна быть конкретизированы для решения части в комментариях:
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# multiproc_sums.py
"""A program that reads integer values from a CSV file and writes out their
sums to another CSV file, using multiple processes if desired.
"""
import csv
import multiprocessing
import optparse
import sys
NUM_PROCS = multiprocessing.cpu_count()
def make_cli_parser():
"""Make the command line interface parser."""
usage = "\n\n".join(["python %prog INPUT_CSV OUTPUT_CSV",
__doc__,
"""
ARGUMENTS:
INPUT_CSV: an input CSV file with rows of numbers
OUTPUT_CSV: an output file that will contain the sums\
"""])
cli_parser = optparse.OptionParser(usage)
cli_parser.add_option('-n', '--numprocs', type='int',
default=NUM_PROCS,
help="Number of processes to launch [DEFAULT: %default]")
return cli_parser
def main(argv):
cli_parser = make_cli_parser()
opts, args = cli_parser.parse_args(argv)
if len(args) != 2:
cli_parser.error("Please provide an input file and output file.")
infile = open(args[0])
in_csvfile = csv.reader(infile)
outfile = open(args[1], 'w')
out_csvfile = csv.writer(outfile)
# Parse the input file and add the parsed data to a queue for
# processing, possibly chunking to decrease communication between
# processes.
# Process the parsed data as soon as any (chunks) appear on the
# queue, using as many processes as allotted by the user
# (opts.numprocs); place results on a queue for output.
#
# Terminate processes when the parser stops putting data in the
# input queue.
# Write the results to disk as soon as they appear on the output
# queue.
# Ensure all child processes have terminated.
# Clean up files.
infile.close()
outfile.close()
if __name__ == '__main__':
main(sys.argv[1:])
Эти фрагменты кода, а также another piece of code that can generate example CSV files для целей тестирования, может быть found on github.
Буду признателен вам за понимание того, как вы, гуру параллелизма, подошли к этой проблеме.
Вот некоторые вопросы, которые я имел, когда речь идет об этой проблеме. Бонусные баллы для решения любой/все:
- Должен ли я иметь дочерние процессы для считывания данных и поместить его в очередь, или может основной процесс сделать это без блокирование, пока все входа прочитали?
- Аналогичным образом, должен ли я иметь дочерний процесс для записи результатов из обработанной очереди или может ли основной процесс сделать это без необходимости ждать всех результатов?
- Должен ли я использовать processes pool для операций с суммой?
- Если да, то какой метод я могу вызвать в пуле, чтобы заставить его начать обработку результатов, поступающих во входную очередь, без блокировки процессов ввода и вывода? apply_async()? map_async()? imap()? imap_unordered()?
- Предположим, что нам не нужно было сифонировать входные и выходные очереди по мере ввода данных, но может дождаться, пока все данные будут проанализированы, и все результаты будут вычислены (например, поскольку мы знаем, что все входные и выходные данные будут вписывается в системную память). Должны ли мы каким-либо образом изменить алгоритм (например, не запускать какие-либо процессы одновременно с I/O)?
Ха-ха, я люблю этот термин смущающе-параллельный. Я удивлен, что это первый раз, когда я услышал этот термин, его отличный способ сослаться на эту концепцию. –