Python多线程学习 setDaemon方法

2024-04-30 15:08

本文主要是介绍Python多线程学习 setDaemon方法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

(2)setDaemon方法:

# -*- coding: utf-8 -*-
import threading
import time
class myThread(threading.Thread):
    def __init__(self, threadname):
        threading.Thread.__init__(self, name=threadname)
       
    def run(self):
        time.sleep(5)
        print '%s is running·······done'%self.getName()
   
t=myThread('son thread')
#t.setDaemon(True)
t.start()
if t.isDaemon():
    print "the father thread and the son thread are done"
else:
    print "the father thread is waiting the son thread····"

 

这段代码的运行流程是:主线程打印完最后一句话后,等待son thread  运行完,然后程序才结束,所以输出结果为:

 

Python代码
  1. the father thread is waitting the son thread····  
  2. son thread is running·······done  
<span style="font-size:24px;">the father thread is waitting the son thread····
son thread is running·······done</span>

 

 

如果启用t.setDaemon(True) ,这段代码的运行流程是:当主线程打印完最后一句话后,不管 son thread 是否运行完,程序立即结束,所以输出结果为:

 

Python代码
  1. the father thread and the son thread are done 

 

 

 

线程的合并
python的Thread类中还提供了join()方法,使得一个线程可以等待另一个线程执行结束后再继续运行。这个方法还可以设定一个timeout参数,避免无休止的等待。因为两个线程顺序完成,看起来象一个线程,所以称为线程的合并。一个例子:


  1. import threading
  2. import random
  3. import time

  4. class MyThread(threading.Thread):

  5.     def run(self):
  6.         wait_time=random.randrange(1,10)
  7.         print "%s will wait %d seconds" % (self.name, wait_time)
  8.         time.sleep(wait_time)
  9.         print "%s finished!" % self.name

  10. if __name__=="__main__":
  11.     threads = []
  12.     for i in range(5):
  13.         t = MyThread()
  14.         t.start()
  15.         threads.append(t)
  16.     print 'main thread is waitting for exit...'        
  17.     for t in threads:
  18.         t.join(1)
  19.         
  20.     print 'main thread finished!'


执行结果:

  1. Thread-1 will wait 3 secondsThread-2 will wait 4 seconds
  2. Thread-3 will wait 1 seconds
  3. Thread-4 will wait 5 seconds
  4. Thread-5 will wait 3 seconds
  5. main thread is waitting for exit...
  6. Thread-3 finished!
  7. Thread-1 finished!
  8. Thread-5 finished!
  9. main thread finished!
  10. Thread-2 finished!
  11. Thread-4 finished!


对于sleep时间过长的线程(这里是2和4),将不被等待。

注意:


Thread.join([timeout])Wait until the thread terminates. This blocks the calling thread until the thread whose join() method is called terminates – either normally or through an unhandled exception – or until the optional timeout occurs.也就是通过传给join一个参数来设置超时,也就是超过指定时间join就不在阻塞进程。而在实际应用测试的时候发现并不是所有的线程在超时时间内都结束的,而是顺序执行检验是否在time_out时间内超时,例如,超时时间设置成2s,前面一个线程在没有完成的情况下,后面线程执行join会从上一个线程结束时间起再设置2s的超时。


根据这段解释,来分析一下程序的运行:


main thread先对Thread-1执行join操作,有1秒的timeout。

当过去1秒之后,main thread发现Thread-1还没有结束(Thread-1需要运行3秒才结束,现在还剩2秒),因此发生timeout,转而继续对Thread-2执行join操作。此次此刻,Thread-3恰巧结束,输入调试语句。


又过去1秒(总共运行了2秒),main thread发现Thread-2也没有结束(Thread-2需要运行4秒才结束,现在还剩2秒),因此同样发生timeout,继续对Thread-3执行join操作。由于Thread-3之前已结束,转而对Thread-4执行join操作。


再过去1秒(总共运行了3秒),main thread发现Thread-4没有结束(Thread-4需要5秒运行,现在还剩2秒),因此发生timeout,继续对Thread-5执行join操作。此时,Thread-1和Thread-5恰巧结束,输出调试语句。

main thread已经完成了对所有需要join的线程的观察和超时,因此main thread线程可以结束了。


时间又经过1秒,Thread-2结束。


再经过1秒,Thread-4结束。



后台线程



默认情况下,主线程在退出时会等待所有子线程的结束如果希望主线程不等待子线程,而是在退出时自动结束所有的子线程,就需要设置子线程为后台线程(daemon)。方法是通过调用线程类的setDaemon()方法。如下:


  1. import threading
  2. import random
  3. import time

  4. class MyThread(threading.Thread):

  5.     def run(self):
  6.         wait_time=random.randrange(1,10)
  7.         print "%s will wait %d seconds" % (self.name, wait_time)
  8.         time.sleep(wait_time)
  9.         print "%s finished!" % self.name

  10. if __name__=="__main__":
  11.     print 'main thread is waitting for exit...'        

  12.     for i in range(5):
  13.         t = MyThread()
  14.         t.setDaemon(True)
  15.         t.start()
  16.         
  17.     print 'main thread finished!'
复制代码



执行结果:

main thread is waitting for exit...
Thread-1 will wait 3 seconds
Thread-2 will wait 3 seconds
Thread-3 will wait 4 seconds
Thread-4 will wait 7 seconds
Thread-5 will wait 7 seconds
main thread finished!
main thread is waitting for exit...
Thread-1 will wait 3 seconds
Thread-2 will wait 3 seconds
Thread-3 will wait 4 seconds
Thread-4 will wait 7 seconds
Thread-5 will wait 7 seconds
main thread finished!

可以看出,主线程没有等待子线程的执行,而直接退出。

小结




join()方法使得线程可以等待另一个线程的运行,而setDaemon()方法使得线程在结束时不等待子线程。join和setDaemon都可以改变线程之间的运行顺序。

 

 

 

 

<span style="font-size:24px;">the father thread and the son thread are done</span>

 

这篇关于Python多线程学习 setDaemon方法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/949195

相关文章

Python通用唯一标识符模块uuid使用案例详解

《Python通用唯一标识符模块uuid使用案例详解》Pythonuuid模块用于生成128位全局唯一标识符,支持UUID1-5版本,适用于分布式系统、数据库主键等场景,需注意隐私、碰撞概率及存储优... 目录简介核心功能1. UUID版本2. UUID属性3. 命名空间使用场景1. 生成唯一标识符2. 数

Java中读取YAML文件配置信息常见问题及解决方法

《Java中读取YAML文件配置信息常见问题及解决方法》:本文主要介绍Java中读取YAML文件配置信息常见问题及解决方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要... 目录1 使用Spring Boot的@ConfigurationProperties2. 使用@Valu

Python办公自动化实战之打造智能邮件发送工具

《Python办公自动化实战之打造智能邮件发送工具》在数字化办公场景中,邮件自动化是提升工作效率的关键技能,本文将演示如何使用Python的smtplib和email库构建一个支持图文混排,多附件,多... 目录前言一、基础配置:搭建邮件发送框架1.1 邮箱服务准备1.2 核心库导入1.3 基础发送函数二、

Javaee多线程之进程和线程之间的区别和联系(最新整理)

《Javaee多线程之进程和线程之间的区别和联系(最新整理)》进程是资源分配单位,线程是调度执行单位,共享资源更高效,创建线程五种方式:继承Thread、Runnable接口、匿名类、lambda,r... 目录进程和线程进程线程进程和线程的区别创建线程的五种写法继承Thread,重写run实现Runnab

Java 方法重载Overload常见误区及注意事项

《Java方法重载Overload常见误区及注意事项》Java方法重载允许同一类中同名方法通过参数类型、数量、顺序差异实现功能扩展,提升代码灵活性,核心条件为参数列表不同,不涉及返回类型、访问修饰符... 目录Java 方法重载(Overload)详解一、方法重载的核心条件二、构成方法重载的具体情况三、不构

Python包管理工具pip的升级指南

《Python包管理工具pip的升级指南》本文全面探讨Python包管理工具pip的升级策略,从基础升级方法到高级技巧,涵盖不同操作系统环境下的最佳实践,我们将深入分析pip的工作原理,介绍多种升级方... 目录1. 背景介绍1.1 目的和范围1.2 预期读者1.3 文档结构概述1.4 术语表1.4.1 核

SQL中如何添加数据(常见方法及示例)

《SQL中如何添加数据(常见方法及示例)》SQL全称为StructuredQueryLanguage,是一种用于管理关系数据库的标准编程语言,下面给大家介绍SQL中如何添加数据,感兴趣的朋友一起看看吧... 目录在mysql中,有多种方法可以添加数据。以下是一些常见的方法及其示例。1. 使用INSERT I

基于Python实现一个图片拆分工具

《基于Python实现一个图片拆分工具》这篇文章主要为大家详细介绍了如何基于Python实现一个图片拆分工具,可以根据需要的行数和列数进行拆分,感兴趣的小伙伴可以跟随小编一起学习一下... 简单介绍先自己选择输入的图片,默认是输出到项目文件夹中,可以自己选择其他的文件夹,选择需要拆分的行数和列数,可以通过

Python中反转字符串的常见方法小结

《Python中反转字符串的常见方法小结》在Python中,字符串对象没有内置的反转方法,然而,在实际开发中,我们经常会遇到需要反转字符串的场景,比如处理回文字符串、文本加密等,因此,掌握如何在Pyt... 目录python中反转字符串的方法技术背景实现步骤1. 使用切片2. 使用 reversed() 函

Python中将嵌套列表扁平化的多种实现方法

《Python中将嵌套列表扁平化的多种实现方法》在Python编程中,我们常常会遇到需要将嵌套列表(即列表中包含列表)转换为一个一维的扁平列表的需求,本文将给大家介绍了多种实现这一目标的方法,需要的朋... 目录python中将嵌套列表扁平化的方法技术背景实现步骤1. 使用嵌套列表推导式2. 使用itert