Làm thế nào để sử dụng multiprocessing để xử lý embarrassingly parallel problems?Giải quyết các vấn đề song song khó xử bằng cách sử dụng đa xử lý Python
vấn đề Embarassingly song song thường bao gồm ba phần cơ bản:
dữ liệu đầu vào- đọc (từ một tập tin, cơ sở dữ liệu, kết nối tcp, vv).
- Chạy các phép tính trên dữ liệu đầu vào, trong đó mỗi phép tính là độc lập với bất kỳ phép tính nào khác.
- Viết kết quả tính toán (vào tệp, cơ sở dữ liệu, kết nối tcp, v.v.).
Chúng ta có thể parallelize chương trình theo hai chiều:
- Phần 2 có thể chạy trên nhiều lõi, vì mỗi tính là độc lập; thứ tự xử lý không quan trọng.
- Mỗi phần có thể chạy độc lập. Phần 1 có thể đặt dữ liệu trên hàng đợi đầu vào, phần 2 có thể kéo dữ liệu ra khỏi hàng đợi đầu vào và đưa kết quả vào hàng đợi đầu ra, và phần 3 có thể kéo kết quả ra khỏi hàng đợi đầu ra và ghi chúng ra.
này dường như là một mô hình cơ bản nhất trong lập trình đồng thời, nhưng tôi vẫn đang bị mất trong cố gắng giải quyết nó, vì vậy chúng ta hãy viết một ví dụ kinh điển để minh họa cách này được thực hiện sử dụng đa xử.
Đây là vấn đề ví dụ: Cho một số CSV file với các hàng số nguyên làm đầu vào, tính tổng của chúng. Tách vấn đề thành ba phần, tất cả có thể chạy song song:
- Process file đầu vào dữ liệu thô (danh sách/iterables các số nguyên)
- Tính số tiền của dữ liệu, song song
- Output số tiền
Dưới đây là truyền thống, đơn quá trình ràng buộc chương trình Python mà giải quyết ba nhiệm vụ:
#!/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:])
Hãy lấy chương trình này và viết lại nó để sử dụng đa xử lý để song song ba phần được nêu ở trên. Dưới đây là bộ xương của mới chương trình này, song song, mà cần phải được fleshed ra để giải quyết những phần trong các ý kiến:
#!/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:])
Những mẩu mã, cũng như another piece of code that can generate example CSV files cho mục đích thử nghiệm, có thể found on github.
Tôi sẽ đánh giá cao bất kỳ thông tin chi tiết nào ở đây về cách thức mà bạn rất kinh nghiệm đồng thời sẽ tiếp cận vấn đề này.
Dưới đây là một số câu hỏi tôi có khi nghĩ về vấn đề này. điểm thưởng để giải quyết bất kỳ/tất cả:
- Tôi có nên có các quy trình con để đọc trong các dữ liệu và đặt nó vào hàng đợi, hoặc quá trình chính có thể làm điều này mà không ngăn chặn cho đến khi tất cả các đầu vào được đọc?
- Tương tự như vậy, tôi có nên có một quy trình con để viết kết quả ra khỏi hàng đợi đã xử lý hay không, quá trình chính có thực hiện được điều này mà không phải đợi tất cả kết quả không?
- Tôi có nên sử dụng processes pool cho tổng số hoạt động không?
- Nếu có, tôi sẽ gọi phương thức nào trên hồ để bắt đầu xử lý kết quả vào hàng đợi nhập, mà không chặn quá trình nhập và xuất? apply_async()? map_async()? imap()? imap_unordered()?
- Giả sử chúng ta không cần phải ngắt hàng đợi đầu vào và đầu ra như dữ liệu đã nhập, nhưng có thể đợi cho đến khi tất cả đầu vào được phân tích và tất cả kết quả được tính toán (ví dụ, vì chúng ta biết tất cả đầu vào và đầu ra sẽ phù hợp với bộ nhớ hệ thống). Chúng tôi có nên thay đổi thuật toán theo bất kỳ cách nào (ví dụ: không chạy bất kỳ quy trình nào đồng thời với I/O) không?
Haha, tôi yêu cụm từ ngượng ngùng song song. Tôi ngạc nhiên rằng đây là lần đầu tiên tôi nghe thuật ngữ này, đó là một cách tuyệt vời để nói đến khái niệm đó. –