day09_02 守护线程

00.threading_ex0 daemon.py

__author__ = "Alex Li"

import threading
import time

# daemon:主线程执行完毕,不管子线程(守护线程)是否执行完毕,等待非守护线程(master)执行完就退出程序
# 与 00.threading_ex0.py执行效果作对比


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(50):
    t = threading.Thread(target=run, args=("t-%s" % i,))
    t.setDaemon(True)  # 把当前线程设置为守护线程,主线程一结束,守护线程就不执行了
    t.start()


print("----------all threads has finished...", threading.current_thread(), threading.active_count())
print("cost:", time.time() - start_time)
# run("t1")
# run("t2")
__author__ = "Alex Li"

import threading
import time


def run(n):
    print("task ", n)
    time.sleep(2)
    # threading.current_thread()用于判断线程类型
    print("task done", n)


'''
# 线程是并行的,输出结果是乱序的
for i in range(5):
    # 线程执行的函数及参数
    t = threading.Thread(target=run, args=("t-%s" %i,))
    # 启动线程
    t.start()
'''

# 单进程运行
run("t1")
run("t2")
posted @ 2021-06-06 14:54  flytoyou  阅读(25)  评论(0编辑  收藏  举报