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

相关文章

Spring Boot Controller处理HTTP请求体的方法

《SpringBootController处理HTTP请求体的方法》SpringBoot提供了强大的机制来处理不同Content-Type​的HTTP请求体,这主要依赖于HttpMessageCo... 目录一、核心机制:HttpMessageConverter​二、按Content-Type​处理详解1.

使用Python实现实时金价监控并自动提醒功能

《使用Python实现实时金价监控并自动提醒功能》在日常投资中,很多朋友喜欢在一些平台买点黄金,低买高卖赚点小差价,但黄金价格实时波动频繁,总是盯着手机太累了,于是我用Python写了一个实时金价监控... 目录工具能干啥?手把手教你用1、先装好这些"食材"2、代码实现讲解1. 用户输入参数2. 设置无头浏

一文教你如何解决Python开发总是import出错的问题

《一文教你如何解决Python开发总是import出错的问题》经常朋友碰到Python开发的过程中import包报错的问题,所以本文将和大家介绍一下可编辑安装(EditableInstall)模式,可... 目录摘要1. 可编辑安装(Editable Install)模式到底在解决什么问题?2. 原理3.

Python+wxPython构建图像编辑器

《Python+wxPython构建图像编辑器》图像编辑应用是学习GUI编程和图像处理的绝佳项目,本教程中,我们将使用wxPython,一个跨平台的PythonGUI工具包,构建一个简单的... 目录引言环境设置创建主窗口加载和显示图像实现绘制工具矩形绘制箭头绘制文字绘制临时绘制处理缩放和旋转缩放旋转保存编

查看MySQL数据库版本的四种方法

《查看MySQL数据库版本的四种方法》查看MySQL数据库的版本信息可以通过多种方法实现,包括使用命令行工具、SQL查询语句和图形化管理工具等,以下是详细的步骤和示例代码,需要的朋友可以参考下... 目录方法一:使用命令行工具1. 使用 mysql 命令示例:方法二:使用 mysqladmin 命令示例:方

Python 异步编程 asyncio简介及基本用法

《Python异步编程asyncio简介及基本用法》asyncio是Python的一个库,用于编写并发代码,使用协程、任务和Futures来处理I/O密集型和高延迟操作,本文给大家介绍Python... 目录1、asyncio是什么IO密集型任务特征2、怎么用1、基本用法2、关键字 async1、async

Python实现剪贴板历史管理器

《Python实现剪贴板历史管理器》在日常工作和编程中,剪贴板是我们使用最频繁的功能之一,本文将介绍如何使用Python和PyQt5开发一个功能强大的剪贴板历史管理器,感兴趣的可以了解下... 目录一、概述:为什么需要剪贴板历史管理二、功能特性全解析2.1 核心功能2.2 增强功能三、效果展示3.1 主界面

Python与Java交互出现乱码的问题解决

《Python与Java交互出现乱码的问题解决》在现代软件开发中,跨语言系统的集成已经成为日常工作的一部分,特别是当Python和Java之间进行交互时,编码问题往往会成为导致数据传输错误、乱码以及难... 目录背景:为什么会出现乱码问题产生的场景解决方案:确保统一的UTF-8编码完整代码示例总结在现代软件

JavaScript时间戳与时间的转化常用方法

《JavaScript时间戳与时间的转化常用方法》在JavaScript中,时间戳(Timestamp)通常指Unix时间戳,即从1970年1月1日00:00:00UTC到某个时间点经过的毫秒数,下面... 目录1. 获取当前时间戳2. 时间戳 → 时间对象3. 时间戳php → 格式化字符串4. 时间字符

Linux区分SSD和机械硬盘的方法总结

《Linux区分SSD和机械硬盘的方法总结》在Linux系统管理中,了解存储设备的类型和特性是至关重要的,不同的存储介质(如固态硬盘SSD和机械硬盘HDD)在性能、可靠性和适用场景上有着显著差异,本文... 目录一、lsblk 命令简介基本用法二、识别磁盘类型的关键参数:ROTA查询 ROTA 参数ROTA