2014-09-03 35 views
2

我想同時啓動2個進程。一個將立即開始處理,另一個將等待第一個進程的觸發器(和參數),以便開始處理。保持進程監聽互通

以下是我的代碼: -

Main.py

packet_obj = packet(i,30,30,30,30,0) 
d = multiprocessing.Process(target = workers.send_trigger_to_controller, args = (packet_obj)) 
d.start() 

# another process should start listening. Something like whenever a trigger is send 
# from the first process, it should then start processing. 

Workers.py

def send_trigger_to_controller(packet_obj): 

    while condition: 

     if condition: 
      d = multiprocessing.Process(target = send_packet_to_controller, args = (sensor_id,high_low,trigger_type)) 
      d.start() 

     elif condition: 
      d = multiprocessing.Process(target = send_packet_to_controller, args = (sensor_id,high_low,trigger_type)) 
      d.start() 

     elif condition: 
      d = multiprocessing.Process(target = send_packet_to_controller, args = (sensor_id,high_low,trigger_type)) 
      d.start() 

至於現在,我開始一個新的進程滿足每個條件。 PS:滿足所有這些條件,但是在不同的時間間隔內,因此取決於時間實例,傳遞不同的參數值。

我想創建一個單一的過程,所有這些都將聽所有這些。如果發送任何觸發器,該進程應該監聽並處理,而不是創建一個完整的新進程。

我該怎麼辦?

+0

這聽起來像你想'Queue'的功能。有一些方法可以在進程之間放置/獲取值(在這種情況下,您的各種參數)。開始一個將隊列傳入的進程,並且滿足各種條件時,將參數放入隊列中,而不是旋轉另一個進程。 – 2014-09-03 08:19:21

回答

2

啓動2個進程並使用隊列(https://docs.python.org/2/library/multiprocessing.html)進行通信。

使用multiprocessing.Process(一個生產者和一個消費者進程)創建2個進程。 生產者是立即開始處理的人,消費者是等待生產者過程準備好的人。

生產者進程完成時將計算結果放入隊列。

消費者進程在隊列中「偵聽」,以及何時有一個項目開始處理。

喜歡的東西:

class ProducerProcess(Process): 

    def __init__(self, q, **kwargs): 
     Process.__init__(self,) 
     self.q = q 

    def run(): 
     res = do_stuff() 
     q.put(res) 

class ConsumerProcess(Process): 

    def __init__(self, q, **kwargs): 
     Process.__init__(self,) 
     self.q = q 

    def run(): 
     while True: 
      args = q.get(block=True) # wait until there is an item in the queue 
      do_stuff(*args) # do stuff here 


q = Queue() 
p1 = ProducerProcess(q, **your_args) 
p2 =ConsumerProcess(q, **extra_args) 
p2.start() 
p1.start() 
# join the processes p1.join() p2.join() or use JoinableQueue depending what you need