2012-12-03 49 views
2

我想提高我的项目使用多处理的速度。在这个玩具环境中的最佳多处理方法

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()) 

这里的问题是,如果一个进程完成建立其东西它会等到其他进程将结束,而我想这样的过程,否则做一些事情。

我该如何做到这一点?我想我可以使用一组工作人员,但我不太了解如何使用它,因为我需要检索结果。有人可以帮忙吗?

回答

0

有一对夫妇的技巧,你可以使用:

  1. 使用共享存储阵列的主要过程和所有的子进程之间的通信。将字典作为输入值,并在输出值计算完毕后设置一个标志。

  2. 使用管道将作业初始化数据从主人传达给工作人员,并将工作人员传回主人。如果可以轻松地序列化数据,这很有效。

这些类的两个在这里详细介绍:http://docs.python.org/2/library/multiprocessing.html

相关问题