the output is like this, so strange, as I thought in the run function, it should also output the list data
list running []
append list [1]
list running []
append list [1, 2]
list running []
append list [1, 2, 3]
list running []
append list [1, 2, 3, 4]
list running []
append list [1, 2, 3, 4, 5]
from multiprocessing import Process
class A(Process):
def __init__(self):
Process.__init__(self)
self.list = []
def append_list(self, item):
self.list.append(item)
print 'append list', self.list
def run(self):
while True:
print 'list running', self.list
import time
time.sleep(2)
a = A()
a.start()
i = 0
while True:
i+=1
import time
time.sleep(2)
a.append_list(i)
the fact that you are calling a function on the process class, doesn’t mean it runs in the sub process.
when you create your A object, the list is in the main process. when you run
start()on it, the list gets copied to the child process (well, not exactly, but let’s assume it for simplicity). then when the parent process calls the function, you are appending to a list that’s only in the memory of the parent process. the one in the child, even though it has the same name, now belongs to a different python process.If you want to share state between processes, you need to use shared memory objects, or queue objects. see here:
http://docs.python.org/library/multiprocessing.html#sharing-state-between-processes