下面是一个简单塞奇纳罗:更新相同的实例变量来自不同进程的
class Test:
def __init__(self):
self.foo = []
def append(self, x):
self.foo.append(x)
def get(self):
return self.foo
def process_append_queue(append_queue, bar):
while True:
x = append_queue.get()
if x is None:
break
bar.append(x)
print("worker done")
def main():
import multiprocessing as mp
bar = Test()
append_queue = mp.Queue(10)
append_queue_process = mp.Process(target=process_append_queue, args=(append_queue, bar))
append_queue_process.start()
for i in range(100):
append_queue.put(i)
append_queue.put(None)
append_queue_process.join()
print str(bar.get())
if __name__=="__main__":
main()
当你在main()
函数结束调用bar.get()
为何仍返回一个空列表?我该如何做到这一点,以便子进程也适用于Test
的同一个实例,而不是一个新实例?
所有答案赞赏!