iis服务器助手广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Python多线程学习 setDae
  • 774
分享到

Python多线程学习 setDae

多线程PythonsetDae 2023-01-31 03:01:14 774人浏览 泡泡鱼

Python 官方文档:入门教程 => 点击学习

摘要

(2)setDaemon方法: # -*- coding: utf-8 -*- import threading import time class myThread(threading.Thread):     def __init

(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>

 

--结束END--

本文标题: Python多线程学习 setDae

本文链接: https://www.lsjlt.com/news/187408.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • Python多线程学习 setDae
    (2)setDaemon方法: # -*- coding: utf-8 -*- import threading import time class myThread(threading.Thread):     def __init...
    99+
    2023-01-31
    多线程 Python setDae
  • python多线程学习
    python多线程学习:python中的线程使用的两种方式:函数或者用类来包装线程对象。1、函数式:调用thread模块中start_new_thread()函数来产生新线程。#!/usr/bin/env python #coding:ut...
    99+
    2023-01-31
    多线程 python
  • Python多线程入门学习
    Python 中使用线程有两种方式:函数或者用类来包装线程对象。 函数式: 调用 thread 模块中的start_new_thread()函数来产生新线程。 语法如下: thr...
    99+
    2024-04-02
  • Python学习记录-多进程和多线程
    [TOC] 1. 进程和线程 进程 狭义定义:进程是正在运行的程序的实例(an instance of a computer program that is being executed)。广义定义:进程是一个具有一定独立功能的程序关于某...
    99+
    2023-01-31
    多线程 进程 Python
  • 学习java多线程
    目录介绍为什么需要多线程线程状态转换线程使用方式继承 Thread 类实现 Runnable 接口实现 Callable 接口同步代码---Runnable接口方式同步方法--Run...
    99+
    2024-04-02
  • python 线程池学习
    #!/usr/bin/pythonimport Queue, threading, sysfrom threading import Threadimport time,urllibclass Worker(Thread):   worke...
    99+
    2023-01-31
    线程 python
  • 深入学习C#多线程
    目录一、基本概念1、进程2、线程二、多线程2.1System.Threading.Thread类2.2 线程的常用属性2.2.1线程的标识符2.2.2线程的优先级别2.2....
    99+
    2024-04-02
  • 多线程学习初步(转)
    import java.io.*;//多线程编程public class MultiThread {public static void main(String args[]){System.out.println("我是主线程!");//...
    99+
    2023-06-03
  • 多线程的学习上篇
    座右铭: 天行健,君子以自强不息;地势坤,君子以厚德载物. 引入进程这个概念的目的 引入进程这个概念,最主要的目的,是为了解决“并发编程"这样的问题. 这是因为CPU进入了多核心的时代 要想进一步提...
    99+
    2023-09-21
    学习 java 服务器
  • Java多线程学习笔记
    目录多任务、多线程程序、进程、线程学着看jdk文档线程的创建1.继承Thread类2.实现Runable接口理解并发的场景龟兔赛跑场景实现callable接口理解函数式接口理解线程的...
    99+
    2024-04-02
  • Python学习教程(Python学习路线):Python——SciPy精讲
    Python学习教程(Python学习路线):Python——SciPy精讲SciPy 是 Python 里处理科学计算 (scientific computing) 的包,使用它遇到问题可访问它的官网 (https://www.scipy...
    99+
    2023-06-02
  • Python学习—python中的线程
    1.线程定义 线程是操作系统能够进行运算调度的最小单位。它被包含在进程之中,是进程中的实际运作单位。一条线程指的是进程中一个单一顺序的控制流,一个进程中可以并发多个线程,每条线程并行执行不同的任务。一个进程至少有一个线程,一个进程必定有一个...
    99+
    2023-01-31
    线程 Python python
  • Java多线程Thread基础学习
    目录1. 创建线程   1.1 通过构造函数:public Thread(Runnable target, String name){}  或:publ...
    99+
    2023-05-17
    Java多线程 Java 多线程Thread
  • Java 多线程学习总结3
    在上一篇中,我们当然希望a++,b++执行完之后,show方法再来show.我们需要的是“原子”动作,一次性地把a++,b++不间断地执行。在java中是利用“互斥”的方法,互斥谁呢?互斥的是相同对象的加锁代码。如果我们把第一篇的SomeB...
    99+
    2023-01-31
    多线程 Java
  • python基础学习20----线程
    什么是线程   线程,有时被称为轻量进程(Lightweight Process,LWP),是程序执行流的最小单元。一个标准的线程由线程ID,当前指令指针(PC),寄存器集合和堆栈组成。另外,线程是进程中的一个实体,是被系统独立调度和分派...
    99+
    2023-01-30
    线程 基础 python
  • Python学习笔记之线程
    目录1.自定义进程2.进程与线程3.多线程4.Thread类方法5.多线程与多进程小Case6.Thread 的生命周期7.自定义线程8.线程共享数据与GIL(全局解释器锁)9.GI...
    99+
    2024-04-02
  • Java学习随记之多线程编程
    Process和Thread 程序是指令和数据的有序集合, 本身没有运行的含义,是一个静态的概念。 进程是执行程序的一次执行过程,他是一个动态的概念,是系统资源分配的单位 一个进程中...
    99+
    2024-04-02
  • Python学习路线
    注意:此文是转载根据本人的学习经验,我总结了以下十点和大家分享:1)学好python的第一步,就是马上到www.python.org网站上下载一个python版本。我建议初学者,不要下载具有IDE功能的集成开发环境,比如Eclipse插件等...
    99+
    2023-01-31
    路线 Python
  • ​Python学习教程_Python学习路线:python—收集系统信息
    Python学习教程(Python学习路线):python—收集系统信息1.1 hashlib模块使用获取文件的MD5值,和shell下的MD5sum一样方法一:先实例化一个对象,再使用update做校验,最后十六进制查看hexdigest...
    99+
    2023-06-02
  • Java多线程之锁学习(增强版)
    目录阻塞锁非阻塞锁锁的四种状态无锁状态偏向锁轻量级锁重量级锁可重入锁自旋锁读写锁互斥锁悲观锁乐观锁公平锁非公平锁显示锁和内置锁轮询锁和定时锁对象锁和类锁锁粗化锁消除信号量独享锁共享锁...
    99+
    2023-02-26
    Java多线程 锁 Java多线程 Java 锁
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作