zoukankan      html  css  js  c++  java
  • 主进程会等待所有子进程执行完后再退出

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

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

    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

    执行结果:

  • 相关阅读:
    Spring Boot第四弹,一文教你如何无感知切换日志框架?
    Spring Boot 第三弹,一文带你了解日志如何配置?
    UVa 1625
    UVa 11584
    UVa 11400
    UVa 12563
    UVa 116
    UVa 1347
    UVa 437
    UVa 1025
  • 原文地址:https://www.cnblogs.com/yujiemeigui/p/14298754.html
Copyright © 2011-2022 走看看