【问题标题】:Communication between parent child processes父子进程之间的通信
【发布时间】:2011-05-23 16:17:12
【问题描述】:

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

父进程产生子进程,然后继续自己的业务,有时我想向特定的子进程发送消息,该子进程捕获它并采取行动。

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

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

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

我的问题是:

  1. 我是不是走错路了
  2. 哪个模块最适合使用
    2.1 我该如何设置

【问题讨论】:

  • 为什么不基于众所周知的IPC机制实现一些东西呢?深入记录了通过共享内存或套接字(TCP/IP 或 Unix 域套接字)进行的通信。

标签: python multithreading python-3.x


【解决方案1】:

请参阅 Doug Hellmann 的(多处理)"Communication Between Processes"。他的 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()

【讨论】:

  • 谢谢大家的投入,目前的工作问题让我把这个爱好项目搁置了几天,但我会看看所有所说的,看看它是否对我有帮助
  • 支持 Doug Hellmann 的(多处理)“进程间通信”链接!
【解决方案2】:

听起来您可能熟悉多处理,只是不熟悉 python。

os.pipe 将为您提供连接父母和孩子的管道。并且semaphores 可用于在父子进程之间协调/发送信号。您可能需要考虑使用queues 来传递消息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-19
    • 1970-01-01
    • 2012-04-15
    • 1970-01-01
    • 1970-01-01
    • 2020-06-26
    • 1970-01-01
    • 2018-09-16
    相关资源
    最近更新 更多