简体   繁体   English

在这种玩具环境中最好的多处理方法

[英]Best multiprocessing approach in this toy environment

I'd like to increase the speed of my project using multiprocessing. 我想使用多处理来提高项目速度。

from multiprocessing import Queue, Process

def build(something):
    # ... Build something ...
    return something

# Things I want to build.
# Each of these things requires DIFFERENT TIME to be built.
some_things = [a_house, a_rocket, a_car]

#________________________________
# My approach

def do_work(queue, func, args):
    queue.put(func(*args))

# Initialize a result queue
queue = Queue()

# Here I'll need to distribute the tasks (in case there are many)
# through each process. For example process 1 build a house and a rocket 
# and so on. Anyway this is not the case..
procs = [Process(target=do_work, args=thing) for thing in some_things]

# Finally, Retrieve things from the queue
results = []
while not queue.empty():
    results.append(queue.get())

Here the problem is that if a process finish to build its stuff it will wait until other processes will finish while I want such process to do something else. 这里的问题是,如果某个进程完成了其内容的构建,它将等待其他进程完成,而我希望该进程执行其他操作。

How can I achieve this? 我该如何实现? I think I could use a pool of workers but I don't really understand how to use it because I need to retrieve the results. 我想我可以使用一批工人,但是我真的不知道如何使用它,因为我需要检索结果。 Can someone help with this? 有人可以帮忙吗?

There are a couple of techniques you can use: 您可以使用两种技术:

  1. Use a shared-memory Array to communicate between the main process and all the child processes. 使用共享内存数组在主进程和所有子进程之间进行通信。 Put dicts as input values and set a flag once an output value has been computed. 将dict作为输入值,并在计算出输出值后设置标记。

  2. Use Pipes to communicate job init data from the master to the workers, and results back from the workers to the master. 使用管道将作业初始化数据从主数据库传递到工作人员,然后将结果从工作人员传递回主数据。 This works well if you can serialize the data easily. 如果您可以轻松地序列化数据,则此方法效果很好。

Both of these classes are detailed here: http://docs.python.org/2/library/multiprocessing.html 这两个类均在此处详细介绍: http : //docs.python.org/2/library/multiprocessing.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM