zoukankan      html  css  js  c++  java
  • Python并发编程-守护进程

    守护进程

    • 子进程转换为守护进程
    • 主进程的代码结束,子进程的代码也应该接收, 这个事情有守护进程来做
    • 守护进程会随着主进程的代码执行完毕而结束, 而不是随着主进程的接收而结束(子进程不一定结束)
    from multiprocessing import Process
    import time
    
    def func():
        while True:
            time.sleep(0.5)
            print('still here')
    
    def func2():
        print('in func 2 start')
        time.sleep(8)
        print('in func 2 finished')
    
    if __name__ == '__main__':
        p = Process(target=func)
        p.daemon = True #必须在start之前设置daemon=True,设置子进程为守护进程
        p.start()
        Process(target=func2).start()
        i = 0
        while i<5:
            print('我是socket server')
            time.sleep(1)
            i += 1
    

    is-alive()判断进程是否还存活, terminate结束一个进程

    • 结束一个进程不是立刻生效,需要一个操作系统响应的过程
    
    from multiprocessing import Process
    import time
    
    def func():
        while True:
            time.sleep(0.5)
            print('still here')
    
    def func2():
        print('in func 2 start')
        time.sleep(8)
        print('in func 2 finished')
    
    if __name__ == '__main__':
        p = Process(target=func)
        p.daemon = True #必须在start之前设置daemon=True,设置子进程为守护进程
        p.start()
        p2 = Process(target=func2)
        p2.start()
        p2.terminate()#结束一个子进程
        print(p2.is_alive())#判断当前进程是否活着
        print(p2.name) #打印当前进程的名字
        time.sleep(2)
        print(p2.is_alive())
    
  • 相关阅读:
    PHP入门
    PHP入门
    PHP入门
    BatsingJSLib 2.3、Ajax上传多个文件
    href的那些事
    从校招网申看华为
    单片机C语言探究--为什么变量最好要赋初值
    Linux学习笔记-Ubuntu添加右键菜单打开终端
    重载--面向对象的鸡肋,强类型语言的软肋
    vs2015发布项目到虚拟主机组策略阻止csc.exe程序问题
  • 原文地址:https://www.cnblogs.com/konglinqingfeng/p/9686380.html
Copyright © 2011-2022 走看看