使用Python的multiprocessing.Process类 [英] Using Python's multiprocessing.Process class

查看:757
本文介绍了使用Python的multiprocessing.Process类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个新手问题:

类是一个对象,所以我可以创建一个 pippo()和这个add函数和参数里面,我不明白如果 pippo 里面的函数从上到下执行,当我分配 x = pippo()或者我必须在之外的 x.dosomething() $ c>。

A class is an object, so I can create a class called pippo() and inside of this add function and parameter, I don't understand if the functions inside of pippo are executed from up to down when I assign x=pippo() or I must call them as x.dosomething() outside of pippo.

使用Python的多处理包,最好定义一个大函数,并使用 target Process()中创建自定义的流程类的$ c>参数,或通过继承 Process

Working with Python's multiprocessing package, is it better to define a big function and create the object using the target argument in the call to Process(), or to create your own process class by inheriting from Process class?

推荐答案

我经常想知道为什么Python的doc页面多处理仅显示功能方法(使用 target 参数)。可能是因为简洁,简洁的代码片段最好是为了说明的目的。对于适合于一个函数的小任务,我可以看到这是首选方法,ala:

I often wondered why Python's doc page on multiprocessing only shows the "functional" approach (using target parameter). Probably because terse, succinct code snippets are best for illustration purposes. For small tasks that fit in one function, I can see how that is the preferred way, ala:

from multiprocessing import Process

def f():
    print('hello')

p = Process(target=f)
p.start()
p.join()

但是当你需要更大的代码组织类是要走的路:

But when you need greater code organization (for complex tasks), making your own class is the way to go:

from multiprocessing import Process

class P(Process):
    def __init__(self):
        super(P, self).__init__()
    def run(self):
        print('hello')

p = P()
p.start()
p.join()

请记住,每个产生的进程获得主进程栈的副本。而且构造函数代码(即 __ init __()中的东西)在主进程中执行 - 只有 run()在单独的进程中执行。当然,如果你的主进程改变了生成的对象的任何成员变量,它将没有效果。相反,对于IPC,使用 multiprocessing.Pipe multiprocessing.Queue

Bear in mind that each spawned process gets a copy of the master process' stack. And that the constructor code (i.e. stuff inside __init__()) is executed in the master process -- only code inside run() executes in separate processes. And, of course, if your master process changes any member variables of your spawned objects, it will have no effect. Instead, for IPC, use multiprocessing.Pipe and multiprocessing.Queue.

这篇关于使用Python的multiprocessing.Process类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆