Skip to main content
 首页 » 编程设计

Python 与空闲进程的进程间通信

2025年05月04日12artech

我有一个空闲的后台进程来处理队列中的数据,我是通过以下方式实现的。此示例中传递的数据只是一个整数,但我将传递最多 1000 个整数的列表,并每秒将最多 100 个列表放入队列。这是正确的方法,还是我应该查看更详细的 RPC 和服务器方法?

import multiprocessing 
import Queue 
import time 
 
class MyProcess(multiprocessing.Process): 
 
    def __init__(self, queue, cmds): 
        multiprocessing.Process.__init__(self)   
        self.q = queue 
        self.cmds = cmds 
 
    def run(self): 
        exit_flag = False 
        while True: 
            try: 
                obj = self.q.get(False) 
                print obj 
            except Queue.Empty: 
                if exit_flag: 
                    break 
                else: 
                    pass 
            if not exit_flag and self.cmds.poll(): 
                cmd = self.cmds.recv() 
                if cmd == -1: 
                    exit_flag = True 
            time.sleep(.01) 
 
if __name__ == '__main__': 
    queue = multiprocessing.Queue() 
    proc2main, main2proc = multiprocessing.Pipe(duplex=False) 
    p = MyProcess(queue, proc2main) 
    p.start() 
    for i in range(5): 
        queue.put(i)     
    main2proc.send(-1) 
    proc2main.close() 
    main2proc.close() 
    # Wait for the worker to finish 
    queue.close() 
    queue.join_thread() 
    p.join() 

请您参考如下方法:

这取决于处理数据需要多长时间。我不能说,因为我没有数据样本,但一般来说,当您需要负载平衡、保证正常运行时间或可扩展性等东西时,最好转向更精细的 RPC 和服务器方法。请记住,这些事情会增加复杂性,这可能会使您的应用程序更难部署、调试和维护。它还会增加处理任务所需的延迟(您可能会或可能不会担心)。

我会用一些示例数据对其进行测试,并确定您是否需要多台服务器提供的可伸缩性。