python 守护进程

守护进程,会随着主进程代码执行结束,而结束

# func1是死循环,如没有守护进程daemon会一直执行下去
# p1是守护进程,主进程的代码执行结束,p1结束
# 注意:在进程开始前,把进程变成守护进程 p.daemon = True
import time
from multiprocessing import Process


def func1():
    while 1:
        print('I want sleep')
        time.sleep(1)


def func2():
    time.sleep(8)
    print('I hate this country')


if __name__ == '__main__':
    p1 = Process(target=func1)
    p1.daemon = True
    p1.start()
    p2 = Process(target=func2)
    p2.start()
    for i in range(3):
        print('wait')
        time.sleep(2)
"""
结果:
wait
I want sleep
I want sleep
wait
I want sleep
I want sleep
wait
I want sleep
I want sleep
I hate this country
"""
"""
其它方法:
p.terminate(),中断进程
p.is_alive(),判断进程是否还活着
p.pid
p.name
"""

 

posted @ 2019-06-18 23:01  市丸银  阅读(206)  评论(0编辑  收藏  举报