gpt4 book ai didi

python - 保持进程监听相互通信

转载 作者:太空宇宙 更新时间:2023-11-04 03:42:30 26 4
gpt4 key购买 nike

我想同时启动 2 个进程。一个将立即开始处理,另一个将等待来自第一个进程的触发器(和参数),以便它开始处理。

以下是我的代码:-

主.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:满足所有这些条件,但在不同的时间间隔,因此根据时间实例,传递不同的参数值。

我想为所有这些创建一个单一进程,它将监听所有这些。如果发送了任何触发器,该进程应该监听然后处理,而不是创建一个完整的新进程。

我该怎么做?

最佳答案

启动 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

关于python - 保持进程监听相互通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25638382/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com