2014-09-03 32 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