Skip to main content
 首页 » 编程设计

python之这个玩具环境中最好的多处理方法

2025年05月04日7hnrainll

我想使用多处理提高我的项目速度。

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

这里的问题是,如果一个进程完成构建它的东西,它将等到其他进程完成,而我希望这样的进程做其他事情。

我怎样才能做到这一点?我想我可以使用一组工作人员,但我真的不明白如何使用它,因为我需要检索结果。有人可以帮忙吗?

请您参考如下方法:

您可以使用一些技巧:

  1. 使用共享内存数组在主进程和所有子进程之间进行通信。将字典作为输入值,并在计算出输出值后设置一个标志。

  2. 使用 Pipes 将作业初始化数据从 master 传递给 workers,并将结果从 workers 返回给 master。如果您可以轻松地序列化数据,这会很有效。

此处详细介绍了这两个类:http://docs.python.org/2/library/multiprocessing.html