为什么`multiprocessing.Process()`在Windows上创建一个中间进程?

时间:2019-04-02 05:30:02

标签: python windows

我正在探索Windows 10上的父子进程关系,并且我已经在python 3.7.2中编写了一个脚本以生成一棵子进程树。我正在使用multiprocessing.Process()生成子进程。每个process记录其process.id,其父级process.id以及它创建的子级process.id

在运行MacOS的本地笔记本电脑上,此行为符合预期;进程1创建进程2323分别报告其父级为1。但是,在Windows上,进程1创建两个进程,例如AB,并且进程23报告A和{{ 1}}分别是他们的父母。为什么创建这些中间过程?为什么不直接生成B2

这是每个系统的脚本和前几个日志文件的输出:

3

来自MacOS的前三个日志(预期行为):

import sys
import os
import time
from multiprocessing import Process

tree = {
    1 : [2, 3],
    2 : [4, 5, 6],
    3 : [7, 8],
    7 : [9, 10]
}

def start_child(my_id):
    children_ids = tree.get(my_id, None)

    child_processes = []
    if children_ids:
        for child_id in children_ids:
            child = Process(target=start_child, args=(child_id,))
            child_processes.append(child)
            child.start()

    current_dir = os.path.dirname(os.path.realpath(__file__))
    with open(f'{current_dir}/{my_id}.log', 'w') as out:
        out.write(f"I am {os.getpid()}.\nMy parent process is {os.getppid()}.\n")
        for child in child_processes:
            out.write(f"I spawned process {child.pid}, named {child.name}.\n")

    time.sleep(50)
    for child in child_processes:
        child.join()

if __name__ == "__main__":
    start_child(1)
# 1.log
I am 40847.
My parent process is 40552.
I spawned process 40857.
I spawned process 40858.
# 2.log
I am 40857.
My parent process is 40847.
I spawned process 40859.
I spawned process 40860.
I spawned process 40862.

来自Windows 10的前三个日志(异常行为):

# 3.log
I am 40858.
My parent process is 40847.
I spawned process 40861.
I spawned process 40863.
# 1.log
I am 6908.
My parent process is 1392.
I spawned process 7608.
I spawned process 5212.
# 2.log
I am 6512.
My parent process is 7608.
I spawned process 10780.
I spawned process 5520.
I spawned process 1176.

正如您在Windows上看到的那样,进程# 3.log I am 2032. My parent process is 5212. I spawned process 3424. I spawned process 7776. process.id的父2是进程3的子进程,而不是进程1本身。

我确定我可以深入研究Windows的1实现,但是我希望其他人已经拥有...

0 个答案:

没有答案