简体   繁体   English

使用Python的multiprocessing.Process类

[英]Using Python's multiprocessing.Process class

This is a newbie question: 这是一个新手问题:

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 . 一个类是一个对象,因此我可以创建一个名为pippo()的类,并在此add函数和参数中创建一个类,当分配x=pippo()时,我不理解pippo内部的函数是否从上到下执行否则我必须在pippo之外将它们称为x.dosomething()

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的多处理程序包,是更好的方法是定义一个大函数并在对Process()的调用中使用target参数创建对象,或者通过从Process类继承来创建自己的Process类?

I often wondered why Python's doc page on multiprocessing only shows the "functional" approach (using target parameter). 我经常想知道为什么Python的有关多处理的doc页面仅显示“功能性”方法(使用target参数)。 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: 对于适合一个功能的小型任务,我可以看到这是首选的方式,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()

Bear in mind that each spawned process is initialized with a copy of the memory footprint of the master process. 请记住,每个生成的进程都使用主进程的内存占用量副本进行初始化。 And that the constructor code (ie stuff inside __init__() ) is executed in the master process -- only code inside run() executes in separate processes. 而且构造函数代码(即__init__() )是在主进程中执行的-仅run()内部的代码在单独的进程中执行。

Therefore, if a process (master or spawned) changes it's member variable, the change will not be reflected in other processes. 因此,如果某个进程(主进程或生成的进程)更改了其成员变量,则该更改将不会反映在其他进程中。 This, of course, is only true for bulit-in types, like bool , string , list , etc. You can however import "special" data structures from multiprocessing module which are then transparently shared between processes (see Sharing state between processes .) Or, you can create your own channels of IPC (inter-process communication) such as multiprocessing.Pipe and multiprocessing.Queue . 当然,这仅适用于boil-in类型,例如boolstringlist等。但是,您可以从multiprocessing模块导入“特殊”数据结构,然后在进程之间透明地共享它们(请参见在进程之间共享状态 。)或者,您可以创建自己的IPC(进程间通信)通道,例如multiprocessing.Pipemultiprocessing.Queue

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

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