原文:http://blog.csdn.net/ice110956/article/details/28421807

Python的多线程有两种实现方法:

函数,线程类

1.函数

调用thread模块中的start_new_thread()函数来创建线程,以线程函数的形式告诉线程该做什么

  1. # -*- coding: utf-8 -*-
  2. import thread
  3. def f(name):
  4. #定义线程函数
  5. print "this is " + name
  6. if __name__ == '__main__':
  7. thread.start_new_thread(f, ("thread1",))
  8. #用start_new_thread()调用线程函数和其他参数
  9. while 1:
  10. pass

不过这种方法暂时没能找到其他辅助方法,连主线程等待都要用while 1这种方法解决。

2.线程类

调用threading模块,创建threading.Thread的子类来得到自定义线程类。

  1. # -*- coding: utf-8 -*-
  2. import threading
  3. class Th(threading.Thread):
  4. def __init__(self, name):
  5. threading.Thread.__init__(self)
  6. self.t_name = name
  7. #调用父类构造函数
  8. def run(self):
  9. #重写run()函数,线程默认从此函数开始执行
  10. print "This is " + self.t_name
  11. if __name__ == '__main__':
  12. thread1 = Th("Thread_1")
  13. thread1.start()
  14. #start()函数启动线程,自动执行run()函数

threading.Thread类的可继承函数:

getName() 获得线程对象名称

setName() 设置线程对象名称

join() 等待调用的线程结束后再运行之后的命令

setDaemon(bool) 阻塞模式,True:父线程不等待子线程结束,False 等待,默认为False

isDaemon() 判断子线程是否和父线程一起结束,即setDaemon()设置的值

isAlive() 判断线程是否在运行

实例

  1. import threading
  2. import time
  3. class Th(threading.Thread):
  4. def __init__(self, thread_name):
  5. threading.Thread.__init__(self)
  6. self.setName(thread_name)
  7. def run(self):
  8. print "This is thread " + self.getName()
  9. for i in range(5):
  10. time.sleep(1)
  11. print str(i)
  12. print self.getName() + "is over"

join()阻塞等待

  1. if __name__ == '__main__':
  2. thread1 = Th("T1 ")
  3. thread1.start()
  4. #thread1.join()
  5. print "main thread is over"

不带thread1.join(),得到如下结果:

This is thread T1

main thread is over

0

1

2

T1 is over

不等待thread1完成,执行之后语句。

加了thread1.join(),得到如下结果:

This is thread T1

0

1

2

T1 is over

main thread is over

阻塞等待thread1结束,才执行下面语句

主线程等待

  1. if __name__ == '__main__':
  2. thread1 = Th("T1 ")
  3. thread1.setDaemon(True)
  4. #要在线程执行之前就设置这个量
  5. thread1.start()
  6. print "main thread is over"

报错:Exception in thread T1  (most likely raised during interpreter shutdown):

也就是主线程不等待子线程就结束了。

多个子线程

  1. if __name__ == '__main__':
  2. for i in range(3):
  3. t = Th(str(i))
  4. t.start()
  5. print "main thread is over"

这里的t可同时处理多个线程,即t为线程句柄,重新赋值不影响线程。

这里奇怪的是,运行t.run()时,不会再执行其他线程。虽不明,还是用start()吧。暂且理解为start()是非阻塞并行的,而run是阻塞的。

线程锁

threading提供线程锁,可以实现线程同步。

  1. import threading
  2. import time
  3. class Th(threading.Thread):
  4. def __init__(self, thread_name):
  5. threading.Thread.__init__(self)
  6. self.setName(thread_name)
  7. def run(self):
  8. threadLock.acquire()
  9. #获得锁之后再运行
  10. print "This is thread " + self.getName()
  11. for i in range(3):
  12. time.sleep(1)
  13. print str(i)
  14. print self.getName() + " is over"
  15. threadLock.release()
  16. #释放锁
  17. if __name__ == '__main__':
  18. threadLock = threading.Lock()
  19. #设置全局锁
  20. thread1 = Th('Thread_1')
  21. thread2 = Th('Thread_2')
  22. thread1.start()
  23. thread2.start()

得到结果:

This is thread Thread_1

0

1

2

Thread_1 is over

This is thread Thread_2

0

1

2

Thread_2 is over

 
 

[Python]多线程入门的更多相关文章

  1. thread/threading——Python多线程入门笔记

    1 什么是线程? (1)线程不同于程序. 线程不能够独立执行,必须依存在应用程序中,由应用程序提供多个线程执行控制: 多线程类似于同时执行多个不同程序. (2)线程不同于进程. 每个独立的进程有一个程 ...

  2. python爬虫入门八:多进程/多线程

    什么是多线程/多进程 引用虫师的解释: 计算机程序只不过是磁盘中可执行的,二进制(或其它类型)的数据.它们只有在被读取到内存中,被操作系统调用的时候才开始它们的生命期. 进程(有时被称为重量级进程)是 ...

  3. Python基础入门教程

    Python基础入门教程 Python基础教程 Python 简介 Python环境搭建 Python 基础语法 Python 变量类型 Python 运算符 Python 条件语句 Python 循 ...

  4. day-3 python多线程编程知识点汇总

    python语言以容易入门,适合应用开发,编程简洁,第三方库多等等诸多优点,并吸引广大编程爱好者.但是也存在一个被熟知的性能瓶颈:python解释器引入GIL锁以后,多CPU场景下,也不再是并行方式运 ...

  5. Python 爬虫入门(二)——爬取妹子图

    Python 爬虫入门 听说你写代码没动力?本文就给你动力,爬取妹子图.如果这也没动力那就没救了. GitHub 地址: https://github.com/injetlee/Python/blob ...

  6. Python 爬虫入门之爬取妹子图

    Python 爬虫入门之爬取妹子图 来源:李英杰  链接: https://segmentfault.com/a/1190000015798452 听说你写代码没动力?本文就给你动力,爬取妹子图.如果 ...

  7. python线程入门

    目录 python线程入门 线程与进程 线程 总结 参考 python线程入门 正常情况下,我们在启动一个程序的时候.这个程序会先启动一个进程,启动之后这个进程会启动起来一个线程.这个线程再去处理事务 ...

  8. Python多线程问题的资料查找与汇总

    Python多线程问题的资料查找与汇总 声明: 1)本报告由博客园bitpeach撰写,版权所有,免费转载,请注明出处,并请勿作商业用途. 2)若本文档内有侵权文字或图片等内容,请联系作者bitpea ...

  9. python多线程爬取世纪佳缘女生资料并简单数据分析

    一. 目标 ​ 作为一只万年单身狗,一直很好奇女生找对象的时候都在想啥呢,这事也不好意思直接问身边的女生,不然别人还以为你要跟她表白啥的,况且工科出身的自己本来接触的女生就少,即使是挨个问遍,样本量也 ...

随机推荐

  1. android.os.handler(转)

    android.os.handler相关知识整理 Handler在android里负责发送和处理消息.它的主要用途有: 1)按计划发送消息或执行某个Runnanble(使用POST方法): 2)从其他 ...

  2. kcon 黑客大会 github

    https://github.com/knownsec/KCon https://paper.seebug.org/107/ CISP认证 https://habo.qq.com/ https://g ...

  3. Delphi 类的类 class of 用法

    http://blog.csdn.net/blue_morning/article/details/8815609 Delphi 类的类 class of 用法   这个概念本来在一个关于Delphi ...

  4. 微软为何选择在 Github 上开源 .NET 核心?

    本文来自微软开源.NET 的一篇公告 ,文中阐述了微软为何选择在 Github 开源.NET,以及微软对开源和开源社区方面的认识的变迁. 对于.NET来说,今天(2014/11/12)是个大日子! 我 ...

  5. 这里包含几乎所有的xcode正式版本

    https://developer.apple.com/downloads/

  6. 在ASP.NET MVC中使用Log4Net记录异常日志,出错时导向到静态页

    本篇体验在ASP.NET MVC 4中使用Log4Net记录日志. 通过NuGet安装Log4Net. 需求是:当出错时导向到Error.html静态页面,Log4Net记录错误信息. 大致的思路是: ...

  7. VS Supercharger插件的破解

    Supercharger我已经用了很多年了,感觉十分不错,最初使用的时候,是叫做CodeMap.不过要想很好的使用起来这个VS插件,需要对其进行细致的设置. 这里不再多说了,看下,这个软件怎么破解吧. ...

  8. 斯巴达克斯血与沙第一季/全集Spartacus迅雷下载

    斯巴达克斯血与沙 第一季Spartacus 1(2010) 本季看点:剧集讲述斯巴达克斯从奴隶变成英雄的血泪辛酸史.被罗马人背叛,流放成奴隶,变为角斗士--这一段罗马共和国历史上最富盛名的传奇故事无人 ...

  9. Adapter数据变化改变现有View的实现原理及案例

    首先说说Adapter详细的类的继承关系.例如以下图 Adapte为接口它的实现类的对象作为AdapterView和View的桥梁,Adapter是装载了View(比方ListView和girdVie ...

  10. Jenkins 快速搭建

    Jenkins 介绍 Jenkins 作为持续集成的重要工具,在DevOps整个工具链中有重要的地位.Jenkins 一般作为独立的应用运行在Java Servlet容器中如Jetty,也可以运行在其 ...