python thread SetDaemon 用法 测试

本文对比了Python中setDaemon(True)与setDaemon(False)的区别,通过实例演示了两种设置下主线程与子线程的执行行为。当主线程结束时,setDaemon(True)将使子线程立即终止,而setDaemon(False)则会等待子线程完成。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

python thread SetDaemon 用法 测试

python2 :
源码如下:

#!/usr/bin/python
#-*- coding:utf-8 -*-
import sys
import threading

import time

class TaskThread(threading.Thread):
    def __init__(self, cnt):
        threading.Thread.__init__(self)
        self.cnt = cnt
    def run(self):

        while self.cnt:
            time.sleep(1)
            print("cnt = %d\n" % self.cnt)
            self.cnt = self.cnt - 1

        print('task thread exit!\n')


if __name__ == "__main__":
    task = TaskThread(10)
    task.setDaemon(True)
    task.start()
    num = 5

    while num:
        time.sleep(1)
        print("num = %d\n" % num)
        num = num - 1

    print('Main Process Exit\n')

运行结果如下:

C:\Python27\python.exe E:/python/work/thread_t1/thread_test1.py
num = 5
cnt = 10


num = 4
cnt = 9


num = 3
cnt = 8


num = 2
cnt = 7


num = 1
cnt = 6


Main Process Exit


Process finished with exit code 0

代码修改为如下形式,
注释掉:task.setDaemon(True)

#!/usr/bin/python
#-*- coding:utf-8 -*-
import sys
import threading

import time

class TaskThread(threading.Thread):
    def __init__(self, cnt):
        threading.Thread.__init__(self)
        self.cnt = cnt
    def run(self):

        while self.cnt:
            time.sleep(1)
            print("cnt = %d\n" % self.cnt)
            self.cnt = self.cnt - 1

        print('task thread exit!\n')


if __name__ == "__main__":
    task = TaskThread(10)
    #task.setDaemon(True)
    task.start()
    num = 5

    while num:
        time.sleep(1)
        print("num = %d\n" % num)
        num = num - 1

    print('Main Process Exit\n')

运行结果:

C:\Python27\python.exe E:/python/work/thread_t1/thread_test1.py
cnt = 10
num = 5


cnt = 9
num = 4


num = 3
cnt = 8


cnt = 7
num = 2


num = 1
cnt = 6


Main Process Exit

cnt = 5

cnt = 4

cnt = 3

cnt = 2

cnt = 1

task thread exit!


Process finished with exit code 0

后台线程与前台线程的直接区别是,
1)setDaemon(True): 当主线程退出时,后台线程随机退出;
2)setDaemon(False)(默认情况): 当主线程退出时,若前台线程还未结束,则等待所有线程结束,相当于在程序末尾加入join().

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值