简体   繁体   English

Python多处理:将数据发送到进程

[英]Python Multiprocessing: Sending data to a process

I have subclassed Process like so: 我有这样的子类化Process

class EdgeRenderer(Process):
    def __init__(self,starter,*args,**kwargs):
        Process.__init__(self,*args,**kwargs)
        self.starter=starter

Then I define a run method which uses self.starter . 然后我定义了一个使用self.starterrun方法。

That starter object is of a class State that I define. starter对象属于我定义的类State

Is it okay that I do this? 我可以这样做吗? What happens to the object? 对象会发生什么? Does it get serialized? 它是否被序列化? Does that mean that I always have to ensure the State object is serializable? 这是否意味着我总是必须确保State对象是可序列化的? Does the new process get a duplicate copy of this object? 新进程是否获得此对象的副本?

On unix systems, multiprocessing uses os.fork() to create the children, on windows, it uses some subprocess trickery and serialization to share the data. 在unix系统上,多处理使用os.fork()来创建子窗口,在Windows上,它使用一些子进程技巧和序列化来共享数据。 So to be cross platform, yes - it must be serializable. 所以要跨平台,是的 - 它必须是可序列化的。 The child will get a new copy. 孩子将获得一份新副本。

That being said, here's an example: 话虽如此,这是一个例子:

from multiprocessing import Process
import time

class Starter(object):
    def __init__(self):
        self.state = False

x = Starter()

class EdgeRenderer(Process):
    def __init__(self,starter,*args,**kwargs):
        Process.__init__(self,*args,**kwargs)
        self.starter=starter
    def run(self):
        self.starter.state = "HAM SANDWICH"
        time.sleep(1)
        print self.starter.state

a = EdgeRenderer(x)
a.start()
x.state = True
a.join()
print x.state

When run, you will see: 运行时,您会看到:

HAM SANDWICH
True

So the changes the parent makes don't get communicated after the fork() and the changes the child makes have the same issue. 因此父进行的更改不会在fork()之后进行通信,并且子进程所做的更改会产生相同的问题。 You have to adhere to fork limitations. 你必须遵守fork限制。

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

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