class 方法进程未更改对象的属性

class method process is not changing objects' attributes

这是我在 Python 的第二天,我发现它是一种非常酷的语言,我想在其中尝试不同的东西。

是否可以调用对象并创建该对象方法的守护进程来更改对象属性?

from multiprocessing import Process
import time


class Foo(object):

    def __init__(self):
        self.number = 1
        # this attribute...

    def loop(self):
        while 1:
            print self.number
            # ...is changed here
            self.number += 1
            time.sleep(1)


if __name__ == '__main__':

    f = Foo()
    p = Process(target=f.loop)
    p.deamon = True # this makes it work in the background

    p.start()

    # proceed with the main loop...
    while 1:
        time.sleep(1)
        print f.number * 10

结果:

1
10
2
10
3
10
4
10
...

为什么 f.loop() 不更改 fself.number?它们都是同一个 class Foo().

的一部分

我可以更改什么来接收此输出:

1
10
2
20
3
30
4
40
...

/编辑 1:

我试过了,结果一样(为什么?):

class Foo(Process):

    def __init__(self):
        super(Foo, self).__init__()
        self.daemon = True # is daemon
        self.number = 1
        self._target = self.loop # on start() it will run loop()

    def loop(self):
        while 1:
            print self.number
            self.number += 1
            time.sleep(1)


if __name__ == '__main__':

    f = Foo() # is now Process

    f.start() # runs f.loop()
    while 1:
        time.sleep(1)
        print f.number * 10

与之前相同的输出。

您正在使用 multiprocessing。简短(并且有些简化)的答案是默认情况下进程不共享内存。请尝试使用 threading

如果您一心想尝试共享内存和进程,请查看有关多处理的文档中的 sharing state

另外 daemon 并不像您认为的那样。如果一个进程创建了子进程,那么它将在退出时尝试杀死所有它的守护进程子进程。所有进程都将在后台运行,您只需要启动它们即可。