我想同时启动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 :(得分: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