主进程会等待所有子进程执行完后再退出

 

 

一、进程的特点:主进程会等待所有子进程执行结束后再结束。

 

解决方法:即让主进程退出后,子进程销毁

1、让子进程设置成为守护主进程

    子进程对象.daemon = True

 

2、让主进程退出之前,先让子进程销毁。

    子进程对象.terminate()

 

二:主进程会等待子进程结束后才能结束

from multiprocessing import *
from time import *


def task():
    for i in range(10):
        print("任务执行中.......")
        sleep(0.2)


if __name__ == '__main__':
    p = Process(target=task)
    p.start()

    # 主进程
    sleep(0.5)
    print("over")
View Code

 

执行结果:

 

 

 

 

 

三、即让主进程退出后,子进程销毁

 

方法一:

from multiprocessing import *
from time import *


def task():
    for i in range(10):
        print("任务执行中.......")
        sleep(0.2)


if __name__ == '__main__':
    p = Process(target=task)
    p.daemon = True # 将子进程设置为守护主进程
    p.start()

    # 主进程
    sleep(0.5)
    print("over")
View Code

 

执行结果:

 

 

 

 

方法二:

 

from multiprocessing import *
from time import *


def task():
    for i in range(10):
        print("任务执行中.......")
        sleep(0.2)


if __name__ == '__main__':
    p = Process(target=task)
    # p.daemon = True # 将子进程设置为守护主进程
    p.start()

    # 主进程
    sleep(0.5)
    p.terminate()  # 退出主进程之前,销毁子进程
    print("over")
View Code

 

执行结果:

 

 

posted @ 2021-01-19 16:48  御姐玫瑰  阅读(550)  评论(0编辑  收藏  举报
levels of contents