python 守护进程

主程序也是一个进程,只是我们看不到,需要借助函数打印。包括子进程也可以打印。

threading.current_thread() 查看当前线程

import threading
import time
def run(n):
    print("task ",n)
    time.sleep(2)
    print('task done',n,threading.current_thread())

start_time = time.time()
t_objs = []
for i in range(5):
    t = threading.Thread(target=run,args=("t-%s" %i,))
    t.start()
    t_objs.append(t)


for t in t_objs:
    t.join()
print('--------------all threads has finished------------',threading.current_thread())
print('cost:',time.time() - start_time )

 运行结果:

task  t-0
task  t-1
task  t-2
task  t-3
task  t-4
task done t-4 <Thread(Thread-5, started 3992)>
task done t-3 <Thread(Thread-4, started 10176)>
task done t-0 <Thread(Thread-1, started 6356)>
task done t-2 <Thread(Thread-3, started 5328)>
task done t-1 <Thread(Thread-2, started 9960)>
--------------all threads has finished------------ <_MainThread(MainThread, started 5628)>
cost: 2.010205030441284

 threading.active_count() 活跃的线程个数

守护线程

守护线程也是子线程,主要是服务于主线程,当主线程退出以后,守护线程也会随之结束。程序会等待非守护线程执行结束以后在退出。

import threading
import time
def run(n):
    print("task ",n)
    time.sleep(2)
    print('task done',n,threading.current_thread())

start_time = time.time()
t_objs = []
for i in range(5):
    t = threading.Thread(target=run,args=("t-%s" %i,))
    t.setDaemon(True)# 把当前线程设置成守护线程
    t.start()
    t_objs.append(t)

print('--------------all threads has finished------------',threading.current_thread(),threading.active_count())
print('cost:',time.time() - start_time )

 执行结果

task  t-0
task  t-1
task  t-2
task  t-3
task  t-4
--------------all threads has finished------------ <_MainThread(MainThread, started 8256)> 6
cost: 0.0010001659393310547

 显示的是有6个子线程,但是程序并没有等待就退出了,原因是没有非守护进程。

 

原文地址:https://www.cnblogs.com/qing-chen/p/7675975.html