python子类化multiprocessing.Process

时间:2011-12-13 13:00:34

标签: python oop concurrency parallel-processing multiprocessing

我是面向python面向对象的新手,我将现有的应用程序重写为面向对象的版本,因为现在开发人员正在增加,而且我的代码变得无法维护。

通常我使用多处理队列,但我从这个例子http://www.doughellmann.com/PyMOTW/multiprocessing/basics.html中发现我可以继承multiprocessing.Process所以我认为这是一个好主意,我写了一个类来测试这样:

代码:

from multiprocessing import Process
class Processor(Process):
    def return_name(self):
        return "Process %s" % self.name
    def run(self):
        return self.return_name()

processes = []


if __name__ == "__main__":

        for i in range(0,5):
                p=Processor()
                processes.append(p)
                p.start()
        for p in processes:
                p.join()

但是我无法取回值,我怎样才能以这种方式使用队列?

编辑:我想获得返回值并考虑将Queues()放在哪里。

4 个答案:

答案 0 :(得分:32)

子类化multiprocessing.Process

  

但是我无法取回值,我怎样才能以这种方式使用队列?

流程需要Queue()才能收到结果......如何继承multiprocessing.Process的示例如下......

from multiprocessing import Process, Queue
class Processor(Process):

    def __init__(self, queue, idx, **kwargs):
        super(Processor, self).__init__()
        self.queue = queue
        self.idx = idx
        self.kwargs = kwargs

    def run(self):
        """Build some CPU-intensive tasks to run via multiprocessing here."""
        hash(self.kwargs) # Shameless usage of CPU for no gain...

        ## Return some information back through multiprocessing.Queue
        ## NOTE: self.name is an attribute of multiprocessing.Process
        self.queue.put("Process idx={0} is called '{1}'".format(self.idx, self.name))

if __name__ == "__main__":
    NUMBER_OF_PROCESSES = 5

    ## Create a list to hold running Processor object instances...
    processes = list()

    q = Queue()  # Build a single queue to send to all process objects...
    for i in range(0, NUMBER_OF_PROCESSES):
        p=Processor(queue=q, idx=i)
        p.start()
        processes.append(p)

    # Incorporating ideas from this answer, below...
    #    https://stackoverflow.com/a/42137966/667301
    [proc.join() for proc in processes]
    while not q.empty():
        print "RESULT: {0}".format(q.get())   # get results from the queue...

在我的机器上,这会导致......

$ python test.py
RESULT: Process idx=0 is called 'Processor-1'
RESULT: Process idx=4 is called 'Processor-5'
RESULT: Process idx=3 is called 'Processor-4'
RESULT: Process idx=1 is called 'Processor-2'
RESULT: Process idx=2 is called 'Processor-3'
$


使用multiprocessing.Pool

FWIW,我发现继承multiprocessing.Process的一个缺点是你无法利用multiprocessing.Pool的所有内在优点;如果您不需要您的生产者和消费者代码通过队列相互交谈,Pool会为您提供一个非常好的API。

您可以使用一些广告素材返回值做很多事情......在以下示例中,我使用dict()来封装来自pool_job()的输入和输出值......

from multiprocessing import Pool

def pool_job(input_val=0):
    # FYI, multiprocessing.Pool can't guarantee that it keeps inputs ordered correctly
    # dict format is {input: output}...
    return {'pool_job(input_val={0})'.format(input_val): int(input_val)*12}

pool = Pool(5)  # Use 5 multiprocessing processes to handle jobs...
results = pool.map(pool_job, xrange(0, 12)) # map xrange(0, 12) into pool_job()
print results

这导致:

[
    {'pool_job(input_val=0)': 0}, 
    {'pool_job(input_val=1)': 12}, 
    {'pool_job(input_val=2)': 24}, 
    {'pool_job(input_val=3)': 36}, 
    {'pool_job(input_val=4)': 48}, 
    {'pool_job(input_val=5)': 60}, 
    {'pool_job(input_val=6)': 72}, 
    {'pool_job(input_val=7)': 84}, 
    {'pool_job(input_val=8)': 96}, 
    {'pool_job(input_val=9)': 108}, 
    {'pool_job(input_val=10)': 120}, 
    {'pool_job(input_val=11)': 132}
]

显然,在pool_job()中还有很多其他改进,例如错误处理,但这说明了基本要点。仅供参考,this answer提供了另一个使用multiprocessing.Pool的示例。

答案 1 :(得分:2)

Process.run的返回值不会消失。您需要将它们发送回父进程,例如使用multiprocessing.Queuedocs here)。

答案 2 :(得分:2)

非常感谢大家。

现在,我是如何完成的:)

在这个例子中我使用多个queus,因为我不想在每个ohter之间进行通信,而只是在父进程之间进行通信。

from multiprocessing import Process,Queue
class Processor(Process):
    def __init__(self,queue):
        Process.__init__(self)
        self.que=queue
    def get_name(self):
        return "Process %s" % self.name
    def run(self):
        self.que.put(self.get_name())



if __name__ == "__main__":

        processes = []
        for i in range(0,5):
                p=Processor(Queue())
                processes.append(p)
                p.start()
        for p in processes:
                p.join()
                print p.que.get()

答案 3 :(得分:2)

Mike's answer是最好的,但为了完整起见,我想提一下,我更喜欢join上下文中收集队列,所以最后一位看起来像这样:

[proc.join() for proc in processes] # 1. join

while not q.empty(): # 2. get the results
    print "RESULT: %s" % q.get()