如何确保父进程不会终止子进程?

时间:2018-03-11 23:56:31

标签: python ubuntu parent-child python-multiprocessing child-process

我有一个父进程在类中运行子进程。子进程需要更长的时间才能完成。我希望确保在父进程终止时子进程不会终止。我该怎么做?

这是我的代码的简化版本:

# myClass.py
from multiprocess import Process
class myClass(self):
    def __init__(self):
        print ('setup the object')
    def parentProcess(self, idx)
        p = Process(target=childFunc)
        p.start()
        time.sleep(3)
        print ('parent is done with ' + str(idx))
    def childProcess(self):
        print ('do some childish stuff')
        time.sleep(8)

这就是我运行父进程的方式

# main.py
from multiprocessing import Process
myClass import myClass
myC = myClass()
for i in range(10):
    p = Process(target=myC.parentProcess, args=i)
    p.start()
    p.join()

1 个答案:

答案 0 :(得分:1)

在完成所有流程之前,您的程序不会终止。试试这个:

from multiprocessing import Process

import time


def foo():
    time.sleep(2)
    print("Now I am done")


if __name__ == "__main__":
    p = Process(target=foo)
    p.start()
    print("I am done.")

但是,要控制流程的执行:

  • 使用child.join()等待子进程结束。

  • 您应该使用两个循环,一个用于启动流程,另一个用于加入它们

试试这个:

from multiprocessing import Process

import time


class MyClass():
    def __init__(self, idx):
        self.idx = idx

    def start_parent(self):
        p = Process(target=self.child_func)
        p.start()
        time.sleep(1)
        print('parent is done, waiting for child', self.idx)
        p.join()
        print('parent exiting', self.idx)

    def child_func(self):
        print('child start', self.idx)
        time.sleep(2)
        print('child end', self.idx)

if __name__ == "__main__":
    parents = []
    for i in range(10):
        o = MyClass(i)
        p = Process(target=o.start_parent)
        parents.append(p)
        p.start()

    for p in parents:
        p.join()

    print("all done")

甚至更好,子类Process并实施run()

from multiprocessing import Process

import time


class ParentProcess(Process):
    def __init__(self, idx, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.idx = idx

    def run(self):
        print('parent start', self.idx)
        child = ChildProcess(self)
        child.start()
        time.sleep(1)
        print('waiting for child', self.idx)
        child.join()
        print('parent end', self.idx)


class ChildProcess(Process):
    def __init__(self, parent, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.parent = parent

    def run(self):
        print('child start', self.parent.idx)
        time.sleep(5)
        print('child end', self.parent.idx)


if __name__ == "__main__":
    parents = [ParentProcess(i) for i in range(10)]
    for p in parents:
        p.start()

    for p in parents:
        p.join()

    print("all done")