父子进程之间的通信

问题描述 投票:0回答:2

我正在尝试创建一个具有一个或多个子进程的 Python 3 程序。

父进程生成子进程,然后继续处理自己的业务,时不时地我想向特定的子进程发送一条消息,该子进程捕获该消息并采取行动。

子进程在等待消息时也需要处于非锁定状态,它将运行自己的循环来维护服务器连接并将任何收到的消息发送到父进程。

我目前正在研究 python 中的多处理、线程、子进程模块,但尚未找到任何解决方案。

我想要实现的是程序的主要部分与用户交互,处理用户输入并向用户呈现信息。 这将与与不同服务器通信的子部分异步,从服务器接收消息并将正确的消息从用户发送到服务器。 然后,子进程会将信息发送回主要部分,在那里它们将被显示给用户

我的问题是:

  1. 我是否以错误的方式处理这个问题
  2. 哪个模块最好用
    2.1 我该如何设置
python multithreading python-3.x
2个回答
7
投票

请参阅 Doug Hellmann 的(多处理)“进程之间的通信”。这是他的本周 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()

3
投票

听起来您可能熟悉多重处理,但不熟悉 python。

os.pipe将为您提供连接父级和子级的管道。 信号量可用于在父子进程之间协调/发出信号。您可能需要考虑使用队列来传递消息。

© www.soinside.com 2019 - 2024. All rights reserved.