在进程上存储对象?

时间:2013-12-19 03:54:19

标签: python multithreading multiprocessing python-multithreading

我想将对象存储在multiprocessing.Process的子类中,如下所示:

class TestProcess( Process ):
    def __init__( self, foo ):
        super( TestProcess, self ).__init__()
        self.foo = foo
    def run( self ):
        from time import sleep
        sleep( 3 )
        self.bar = self.foo

p = TestProcess( 5 )
p.start()
p.join()
print( p.bar ) # raises AttributeError

使用Process切换Thread时效果很好,但我显然遗漏了一些东西。什么?

2 个答案:

答案 0 :(得分:3)

由于TestProcess.run()正在子进程中运行,因此它会在子进程中分配self.bar,这不会影响父进程。 以下代码将向您显示不同的内容:

import os
from multiprocessing import Process, Queue

class TestProcess( Process ):
    def __init__( self, foo ):
        super( TestProcess, self ).__init__()
        self.foo = foo
        self.bar = None
        self.que = Queue()
    def run( self ):
        from time import sleep
        sleep( 1 )
        self.bar = self.foo
        print( "pid2=%s, p.bar=%s" % (os.getpid(), self.bar ))
        self.que.put(self.bar)

p = TestProcess( 5 )
p.start()
p.join()
print( "pid1=%s, p.bar=%s" % (os.getpid(), p.bar ))
print(p.que.get())

您将看到pid1和pid2不同。当然,如果你使用Thread,它们会在同一个进程中运行,所以它可以工作。

如果确实需要在子进程中存储数据,则转移到父进程,然后进行进程间通信。您可以使用队列。

答案 1 :(得分:1)

当您从threading切换到multiprocessing并返回时,您将从每个线程共享相同内存的环境切换到不共享任何内容的环境,除非明确共享。如果要在进程之间共享变量,可以使用ValueArray,其中一个Queue类或另一个共享结构。

import os
from multiprocessing import Process, Value

class TestProcess( Process ):
    def __init__( self, foo ):
        super( TestProcess, self ).__init__()
        self.foo = foo
        self.bar = Value('i', 0)
    def run( self ):
        from time import sleep
        sleep( 1 )
        self.bar.value = self.foo
        print( "pid2=%s, p.bar=%s" % (os.getpid(), self.bar.value ))

p = TestProcess( 5 )
p.start()
p.join()
print( "pid1=%s, p.bar=%s" % (os.getpid(), p.bar.value ))
print(p.bar.value)