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

2024-10-02 18:16:55 发布

您现在位置:Python中文网/ 问答频道 /正文

在下面的程序中,当我将进程附加到一个列表(一个看起来毫无意义的事情)时,它按预期运行。但是如果我删除了append,进程析构函数在它运行之前会被调用很多次。只有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')

带append的示例输出:

^{pr2}$

不带附加的示例输出:

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

Tags: inselffor进程过程defrangemultiprocessing
1条回答
网友
1楼 · 发布于 2024-10-02 18:16:55

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

相关代码正在多处理中/分叉.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)

其中,bootstrap设置新进程并调用“run”(代码在多处理中)/进程.py)在

相关问题 更多 >