利用 Python 中的多进程实现父子进程通信

135 阅读2分钟

我们希望创建一个 Python 3 程序,其中包含一个或多个子进程。父进程生成子进程,然后继续运行自己的业务。在此期间,我们希望能够向特定的子进程发送消息,由该子进程接收并采取行动。此外,子进程在等待消息时不能被锁住,它将运行自己的循环来维护服务器连接,并将收到的任何消息发送给父进程。

我们目前正在研究 Python 中的多处理、线程和子进程模块,但尚未找到任何解决方案。我们想要实现的是一个与用户交互的程序主部分,它负责处理用户输入并向用户呈现信息。这将与子部分异步运行,子部分与不同的服务器进行通信,从服务器接收消息并从用户向服务器发送正确的消息。然后,子进程将信息发送回主部分,在主部分中将这些信息呈现给用户。

我们的问题是:

  • 我们是否采用了错误的方法?
  • 哪个模块最适合使用?
  • 我们该如何设置它?

2、解决方案

使用 Python 中的多处理模块实现父子进程间的通信

import time
from multiprocessing import Process, Manager

def test_f(test_d):
   """  frist process to run
        exit this process when dictionary's 'QUIT' == True
   """
   test_d['2'] = 2     ## change to test this
   while not test_d["QUIT"]:
      print "test_f", test_d["QUIT"]
      test_d["ctr"] += 1
      time.sleep(1.0)

def test_f2(name):
    """ second process to run.  Runs until the for loop exits
    """
    for j in range(0, 10):
       print name, j
       time.sleep(0.5)

    print "second process finished"

if __name__ == '__main__':
    ##--- create a dictionary via Manager
    manager = Manager()
    test_d = manager.dict()
    test_d["ctr"] = 0
    test_d["QUIT"] = False

    ##---  start first process and send dictionary
    p = Process(target=test_f, args=(test_d,))
    p.start()

    ##--- start second process
    p2 = Process(target=test_f2, args=('P2',))
    p2.start()

    ##--- sleep 3 seconds and then change dictionary
    ##     to exit first process
    time.sleep(3.0)
    print "\n terminate first process"
    test_d["QUIT"] = True
    print "test_d changed"
    print "data from first process", test_d

    time.sleep(5.0)
    p.terminate()
    p2.terminate()
  • 解释:

    这段代码使用 Python 3 的多处理模块来创建一个父进程和两个子进程。父进程创建并启动子进程,然后继续运行自己的循环。子进程在等待来自父进程的消息时运行自己的循环。当父进程向子进程发送消息时,子进程收到消息并采取行动。示例中,父子进程之间的数据通信是通过一个共享字典 test_d 来实现的。

  • 优点:

    • 这是一种在 Python 中实现父子进程通信的简单而有效的方法。
    • 它很容易理解和实现。
    • 它可以用于各种各样的应用程序。
  • 缺点:

    • 它可能不是最有效的方法,因为子进程在等待消息时需要不断地轮询共享字典。
    • 它可能不是最安全的,因为它依赖于共享内存,如果子进程崩溃,可能会导致数据损坏。