将进程附加到列表(但不对其执行任何操作)会改变程序行为

tjm*_*tjm 8 python subprocess multiprocessing python-3.x

在下面的程序中,当我将进程附加到列表(看似毫无意义的事情)时,它会按预期运行.但是如果我删除了追加,那么进程析构函数在它运行之前会被多次调用.只有n结构,但(n)(n+1)/2(n进程数)在哪里析构.这使我相信每个进程都被复制到每个新进程中,然后立即被销毁.也许这就是多处理模块的工作原理.这是有道理的,因为每个进程都是当前进程的一个分支.但是,附加到列表的重要性是什么?为什么简单地这样做会阻止这种行为?

这是测试和示例输出:

import multiprocessing

class _ProcSTOP:
    pass

class Proc(multiprocessing.Process):

    def __init__(self, q, s): 
        s.i += 1
        self._i = s.i 
        self._q = q 
        print('constructing:', s.i)
        super().__init__()

    def run(self):
        dat = self._q.get()

        while not dat is _ProcSTOP:
            self._q.task_done()
            dat = self._q.get()

        self._q.task_done()
        print('returning:   ', self._i)

    def __del__(self):
        print('destroying:  ', self._i)



if __name__ == '__main__':

    q = multiprocessing.JoinableQueue()
    s = multiprocessing.Manager().Namespace()
    s.i = 0 
    pool = []

    for i in range(4):
        p = Proc(q, s)
        p.start()
        pool.append(p)    # This is the line to comment

    for i in range(10000):
        q.put(i)

    q.join()

    for i in range(4):
        q.put(_ProcSTOP)

    q.join()

    print('== complete')
Run Code Online (Sandbox Code Playgroud)

带附加的示例输出:

constructing: 1
constructing: 2
constructing: 3
constructing: 4
returning:    3
returning:    2
== complete
returning:    1
returning:    4
destroying:   4
destroying:   3
destroying:   2
destroying:   1
Run Code Online (Sandbox Code Playgroud)

样品输出没有追加:

constructing: 1
constructing: 2
constructing: 3
destroying:   1
constructing: 4
destroying:   1
destroying:   2
destroying:   3
destroying:   1
destroying:   2
returning:    1
returning:    4
returning:    2
== complete
returning:    3
destroying:   1
destroying:   3
destroying:   2
destroying:   4
Run Code Online (Sandbox Code Playgroud)

Mih*_*tan 1

将对象添加到列表中将防止它在子进程中被删除,因为分叉后它将调用“os._exit()”而不是清除整个堆栈

相关代码位于multiprocessing/forking.py(Popen的构造函数,在“p.start()”上调用)

 self.pid = os.fork()
 if self.pid == 0:
     if 'random' in sys.modules:
         import random
         random.seed()
     code = process_obj._bootstrap()
     sys.stdout.flush()
     sys.stderr.flush()
     os._exit(code)
Run Code Online (Sandbox Code Playgroud)

其中 _bootstrap 设置新进程并调用“run”(代码位于 multiprocessing/process.py 中)