2015-10-19 38 views
0

我的目标是创建两个交互的对象,特别是创建数据并将其附加到列表的另一个对象,以及可以检查该列表并输出数据的另一个对象。如何创建两个可以相互监视的对象?

基于另一个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) 

那么理想,无论是在同一时间运行的过程中。然而,最终发生的是第一个对象被创建,发出所有数据,然后第二个对象运行,而不是同时运行。它的工作原理是它们可以共享数据,但它们在同时运行的意义上不起作用。

(这是一本书的练习,从班章,但他们并没有真正讨论如何做到这一点做)

+2

你需要更具体的了解你的意思是什么“与此同时”。一种可能性是让A的方法只生成少量的数据,而B的方法只消耗少量的数据,并让“主”管理一个“事件循环”,依次调用这两种方法,所以只能与主人,而不是A和B对象本身。在任何情况下,“__init__”不应该在“同时”执行任何操作。 – BrenBarn

回答

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() 
+0

'我'始终是零,它的正方形都是零 – Pynchia

+0

@Pynchia:很好!我忘了增加。谢谢你让我知道:) – inspectorG4dget

+0

这样做的工作与对象?我没有完全说明如何将这些代码调整为创建对象,而不是调用一个函数。 – goodtimeslim

相关问题