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

标签 python multiprocessing

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

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

我该怎么做?

最佳答案

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

相关文章:

python - django 中模板的自定义加载器的单元测试用例存在问题

python - 处理 Word 文档的最佳方式

python - 以串行对象为参数的多进程

Python多进程调试

python - Perforce (P4) Python API 提示锁太多

python - 如何在 gdb 中使用 IPython 交互式 shell? ||如何在 gdb 的 Python 交互式 (pi) shell 中使用制表符补全功能?

python - 在 Python 中导入模块的文件夹

python - 使用 python 多重处理读取多个 CSV 文件并将数据插入表中,而不使用 pandas

python - 结合 itertools 和多处理?

python - py.test : how to automatically detect an exception in a child process?