我的目标是创建两个交互的对象,特别是一个创建数据并将其附加到列表的对象,以及另一个可以检查该列表并输出数据的对象。
根据另一个stackoverflow问题,有人建议创建第三个对象来存储数据,然后让前两个对象启动。
代码的工作原理如下:
class Master:
def __init__(self):
self.data = []
(some methods for interaction)
class A:
def __init__(self, master_instance):
...
self.master_instance = master_instance
(call method that randomly generates data and adds it to the master_instance data
, and run this for a while (essentially as long as I want this process to continue))
def my_a_method(self):
...
class B:
def __init__(self, master_instance):
...
self.master_instance = master_instance
(call method that monitors master_instance to see if object A has added any data
to it, and spit it out. Like above, run this for as long as I want the process
to continue)
def my_b_method(self):
...
master = Master()
a = A(master)
b = B(master)
理想情况下,这两个过程同时运行。然而,最终发生的是第一个对象被创建,发送出所有数据,然后第二个对象运行,而不是同时运行。它的工作原理是它们可以共享数据,但它们在同时运行时并不起作用。
(这是一本书中的练习,来自关于课程的章节,但他们并没有真正讨论如何做到这一点)
答案 0 :(得分:3)
import multiprocessing as mp
queue = mp.Queue()
def adder(q): # for the sake of this example, let's say we want to add squares of all numbers to the queue
i = 0
while i < 100:
q.put(i**2)
i += 1
q.put(None)
def monitor(q): # monitor the queue and do stuff with the data therein
for e in iter(q.get, None):
print(e) # for now, let's just print the stuff
a = mp.Process(target=adder, args=(queue,))
b = mp.Process(target=monitor, args=(queue,))
a.start()
b.start()
a.join() # wait for the process to finish
b.join() # wait for the process to finish (both processes running simultaneously)
a.terminate()
b.terminate()