2015-10-19 78 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

相關問題