Python多线程-守护线程

守护线程:守护着非守护线程,守护线程和非守护线程同时运行,当非守护线程运行结束后,无论守护线程有没有运行完,脚本都会停止运行

首先看一段普通的多线程实例

# -*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR"

import threading
import time

def MyThread(n):
    print("Running %s Thread"%n)
    time.sleep(2)
    print(n,"Thread has slept 2s")

for i in range(20):
    t = threading.Thread(target=MyThread,args=(i,))
    t.start()

print("-----The Main Thread-----")

 运行结果

所有线程结束后,脚本才结束运行

将子线程设置为守护线程

# -*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR"

import threading
import time

def MyThread(n):
    print("Running %s Thread"%n)
    time.sleep(2)
    print(n,"Thread has slept 2s")

for i in range(20):
    t = threading.Thread(target=MyThread,args=(i,))
    t.setDaemon(True) #将该线程设置为守护线程
    t.start()

print("-----The Main Thread-----")

 运行结果

非守护线程(主线程)运行完,守护线程(子线程)没有全部运行完,脚本就退出了

posted @ 2017-12-14 14:20  Sch01aR#  阅读(459)  评论(0编辑  收藏  举报