在下面的代碼中,如何使Starter
對象能夠讀取gen.vals
? 這似乎是一個不同的對象被創建,其狀態得到更新,但絕不Starter
知道這事。此外,該解決方案將如何申請self.vals
是一本字典,或任何其他類型的對象?跨進程共享對象狀態?
import multiprocessing
import time
class Generator(multiprocessing.Process):
def __init__(self):
self.vals = []
super(Generator, self).__init__()
def run(self):
i = 0
while True:
time.sleep(1)
self.vals.append(i)
print 'In Generator ', self.vals # prints growing list
i += 1
class Starter():
def do_stuff(self):
gen = Generator()
gen.start()
while True:
print 'In Starter ', gen.vals # prints empty list
time.sleep(1)
if __name__ == '__main__':
starter = Starter()
starter.do_stuff()
輸出:
In Starter []
In Starter []
In Generator [0]
In Starter []
In Generator [0, 1]
In Starter []
In Generator [0, 1, 2]
In Starter []
In Generator [0, 1, 2, 3]
In Starter []
In Generator [0, 1, 2, 3, 4]
In Starter []
In Generator [0, 1, 2, 3, 4, 5]
In Starter []
In Generator [0, 1, 2, 3, 4, 5, 6]
In Starter []
In Generator [0, 1, 2, 3, 4, 5, 6, 7]
https://docs.python.org/2/library/multiprocessing.html。第16.6.1.4節 –
您是否願意演示該示例的解決方案?這是一個最小的,自包含的,可重複的例子,所以它不應該很難。 –