将串行任务转换为并行以映射输入和输出

时间:2013-07-04 05:22:17

标签: python parallel-processing multiprocessing

我有数万个模拟在具有多个核心的系统上运行。目前,它是以串行方式完成的,我知道输入参数,并将结果存储在dict中。

串行版

import time
import random

class MyModel(object):
    input = None
    output = None

    def run(self):
        time.sleep(random.random())  # simulate a complex task
        self.output = self.input * 10


# Run serial tasks and store results for each parameter

parameters = range(10)
results = {}

for p in parameters:
    m = MyModel()
    m.input = p
    m.run()
    results[p] = m.output

print('results: ' + str(results))

小于< 10秒,并显示正确的结果:

results: {0: 0, 1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60, 7: 70, 8: 80, 9: 90}

并行版

我尝试并行化此过程是基于文本"An example showing how to use queues to feed tasks to a collection of worker processes and collect the results"附近的multiprocessing模块中的示例(抱歉,没有可用的URL锚点)。

以下内容建立在串行版本的上半部分:

from multiprocessing import Process, Queue
NUMBER_OF_PROCESSES = 4

def worker(input, output):
    for args in iter(input.get, 'STOP'):
        m = MyModel()
        m.input = args[0]
        m.run()
        output.put(m.output)


# Run parallel tasks and store results for each parameter

parameters = range(10)
results = {}

# Create queues
task_queue = Queue()
done_queue = Queue()

# Submit tasks
tasks = [(t,) for t in parameters]
for task in tasks:
    task_queue.put(task)

# Start worker processes
for i in range(NUMBER_OF_PROCESSES):
    Process(target=worker, args=(task_queue, done_queue)).start()

# Get unordered results
for i in range(len(tasks)):
    results[i] = done_queue.get()

# Tell child processes to stop
for i in range(NUMBER_OF_PROCESSES):
    task_queue.put('STOP')

print('results: ' + str(results))

现在只需几秒钟,但输入和结果之间的映射顺序混合在一起。

results: {0: 10, 1: 0, 2: 60, 3: 40, 4: 20, 5: 80, 6: 30, 7: 90, 8: 70, 9: 50}

我意识到我正在根据无序results填充done_queue.get(),但我不确定如何将正确的映射到task_queue。有任何想法吗?还有什么方法可以让它变得更干净吗?

1 个答案:

答案 0 :(得分:1)

A-公顷! worker需要嵌入某种ID,例如用于返回输出队列的输入参数,这些ID可用于标识返回的进程。以下是必要的修改:

def worker(input, output):
    for args in iter(input.get, 'STOP'):
        m = MyModel()
        m.input = args[0]
        m.run()
        # Return a tuple of an ID (the input parameter), and the model output
        return_obj = (m.input, m.output)
        output.put(return_obj)

# Get unordered results
for i in range(len(tasks)):
    # Unravel output tuple, which has the input parameter 'p' used as an ID
    p, result = done_queue.get()
    results[p] = result