Python线程创建和终止实例代码


Posted in Python onJanuary 20, 2018

python主要是通过thread和threading这两个模块来实现多线程支持。

python的thread模块是比?底层的模块,python的threading模块是对thread做了一些封装,能够更加方便的被使用。可是python(cpython)因为GIL的存在无法使用threading充分利用CPU资源,假设想充分发挥多核CPU的计算能力须要使用multiprocessing模块(Windows下使用会有诸多问题)。

假设在对线程应用有较高的要求时能够考虑使用Stackless Python来完毕。Stackless Python是Python的一个改动版本号,对多线程编程有更好的支持,提供了对微线程的支持。微线程是轻量级的线程,在多个线程间切换所需的时间很多其它,占用资源也更少。

通过threading模块创建新的线程有两种方法:一种是通过threading.Thread(Target=executable Method)-即传递给Thread对象一个可运行方法(或对象);另外一种是继承threading.Thread定义子类并重写run()方法。另外一种方法中,唯一必须重写的方法是run(),可依据需要决定是否重写__init__()。值得注意的是,若要重写__init__(),父类的__init__()必需要在函数第一行调用,否则会触发错误“AssertionError: Thread.__init__() not called”

Python threading模块不同于其它语言之处在于它没有提供线程的终止方法,通过Python threading.Thread()启动的线程彼此是独立的。若在线程A中启动了线程B,那么A、B是彼此独立执行的线程。若想终止线程A的同一时候强力终止线程B。一个简单的方法是通过在线程A中调用B.setDaemon(True)实现。

但这样带来的问题是:线程B中的资源(打开的文件、传输数据等)可能会没有正确的释放。所以setDaemon()并不是一个好方法,更为妥当的方式是通过Event机制。以下这段程序体现了setDaemon()和Event机制终止子线程的差别。

import threading 
import time 
class mythread(threading.Thread): 
 def __init__(self,stopevt = None,File=None,name = 'subthread',Type ='event'): 
  threading.Thread.__init__(self) 
  self.stopevt = stopevt 
  self.name = name 
  self.File = File 
  self.Type = Type 
   
     
 def Eventrun(self): 
  while not self.stopevt.isSet(): 
   print self.name +' alive\n' 
   time.sleep(2) 
  if self.File: 
   print 'close opened file in '+self.name+'\n' 
   self.File.close() 
  print self.name +' stoped\n' 
  
 def Daemonrun(self): 
  D = mythreadDaemon(self.File) 
  D.setDaemon(True) 
  while not self.stopevt.isSet(): 
   print self.name +' alive\n' 
   time.sleep(2) 
  print self.name +' stoped\n' 
 def run(self): 
  if self.Type == 'event': self.Eventrun() 
  else: self.Daemonrun() 
class mythreadDaemon(threading.Thread): 
 def __init__(self,File=None,name = 'Daemonthread'): 
  threading.Thread.__init__(self) 
  self.name = name 
  self.File = File 
 def run(self): 
  while True: 
   print self.name +' alive\n' 
   time.sleep(2) 
  if self.File: 
   print 'close opened file in '+self.name+'\n' 
   self.File.close() 
  print self.name +' stoped\n' 
   
def evtstop(): 
 stopevt = threading.Event() 
 FileA = open('testA.txt','w') 
 FileB = open('testB.txt','w') 
 A = mythread(stopevt,FileA,'subthreadA') 
 B = mythread(stopevt,FileB,'subthreadB') 
 print repr(threading.currentThread())+'alive\n' 
 print FileA.name + ' closed?
 '+repr(FileA.closed)+'\n' 
 print FileB.name + ' closed? '+repr(FileB.closed)+'\n' 
 A.start() 
 B.start() 
 time.sleep(1) 
 print repr(threading.currentThread())+'send stop signal\n' 
 stopevt.set() 
 A.join() 
 B.join() 
 print repr(threading.currentThread())+'stoped\n' 
 print 'after A stoped, '+FileA.name + ' closed? '+repr(FileA.closed)+'\n' 
 print 'after A stoped, '+FileB.name + ' closed?

 '+repr(FileB.closed)+'\n' 
def daemonstop(): 
 stopevt = threading.Event() 
 FileA = open('testA.txt','r') 
 A = mythread(stopevt,FileA,'subthreadA',Type = 'Daemon') 
 print repr(threading.currentThread())+'alive\n' 
 print FileA.name + ' closed?

 '+repr(FileA.closed)+'\n' 
 A.start() 
 time.sleep(1) 
 stopevt.set() 
 A.join() 
 print repr(threading.currentThread())+'stoped\n' 
 print 'after A stoped, '+FileA.name + ' closed? '+repr(FileA.closed)+'\n' 
 if not FileA.closed: 
  print 'You see the differents, the resource in subthread may not released with setDaemon()' 
  FileA.close() 
if __name__ =='__main__': 
 print '-------stop subthread example with Event:----------\n' 
 evtstop() 
 print '-------Daemon stop subthread example :----------\n' 
 daemonstop()

执行结果是:

-------stop subthread example with Event:---------- 
<_MainThread(MainThread, started 2436)>alive 
testA.txt closed?
 False 
testB.txt closed? False 
subthreadA alive 
subthreadB alive 
 
<_MainThread(MainThread, started 2436)>send stop signal 
close opened file in subthreadA 
close opened file in subthreadB 
 
subthreadA stoped 
subthreadB stoped 
 
<_MainThread(MainThread, started 2436)>stoped 
after A stoped, testA.txt closed? True 
after A stoped, testB.txt closed?

 True 
-------Daemon stop subthread example :---------- 
<_MainThread(MainThread, started 2436)>alive 
testA.txt closed?

 False 
subthreadA alive 
subthreadA stoped 
<_MainThread(MainThread, started 2436)>stoped 
after A stoped, testA.txt closed? False 
You see the differents, the resource in subthread may not released with setDaemon()

总结

以上就是本文关于Python线程创建和终止实例代码的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

Python 相关文章推荐
Python中为什么要用self探讨
Apr 14 Python
Python中json格式数据的编码与解码方法详解
Jul 01 Python
python嵌套字典比较值与取值的实现示例
Nov 03 Python
基于并发服务器几种实现方法(总结)
Dec 29 Python
django使用xlwt导出excel文件实例代码
Feb 06 Python
使用python脚本实现查询火车票工具
Jul 19 Python
python requests.post带head和body的实例
Jan 02 Python
Pandas中resample方法详解
Jul 02 Python
命令行运行Python脚本时传入参数的三种方式详解
Oct 11 Python
Tensorflow 多线程设置方式
Feb 06 Python
python dict乱码如何解决
Jun 07 Python
pycharm如何设置官方中文(如何汉化)
Dec 29 Python
python+matplotlib实现动态绘制图片实例代码(交互式绘图)
Jan 20 #Python
Python实现PS滤镜的旋转模糊功能示例
Jan 20 #Python
浅谈flask中的before_request与after_request
Jan 20 #Python
Python使用SQLite和Excel操作进行数据分析
Jan 20 #Python
python与sqlite3实现解密chrome cookie实例代码
Jan 20 #Python
Python实现PS滤镜中马赛克效果示例
Jan 20 #Python
浅析python协程相关概念
Jan 20 #Python
You might like
php生成随机数或者字符串的代码
2008/09/05 PHP
php设计模式小结
2013/02/15 PHP
PHP的MVC模式实现原理分析(一相简单的MVC框架范例)
2014/04/29 PHP
CI框架出现mysql数据库连接资源无法释放的解决方法
2016/05/17 PHP
Laravel中使用FormRequest进行表单验证方法及问题汇总
2016/06/19 PHP
PHP 根据key 给二维数组分组
2016/12/09 PHP
Laravel框架处理用户的请求操作详解
2019/12/20 PHP
jquery验证手机号码、邮箱格式是否正确示例代码
2013/07/28 Javascript
JAVASCRIPT函数作用域和提前声明 分享
2013/08/22 Javascript
JsRender实用入门教程
2014/10/31 Javascript
JS实现跟随鼠标立体翻转图片的方法
2015/05/04 Javascript
JS+CSS实现仿触屏手机拨号盘界面及功能模拟完整实例
2015/05/16 Javascript
AngularJS入门教程之AngularJS模型
2016/04/18 Javascript
jquery.validate[.unobtrusive]和Bootstrap实现tooltip错误提示问题分析
2016/10/30 Javascript
web前端vue filter 过滤器
2018/01/12 Javascript
vue计算属性computed的使用方法示例
2019/03/13 Javascript
微信小程序 行的删除和增加操作实现详解
2019/09/29 Javascript
[01:10:16]DOTA2上海特级锦标赛B组资格赛#2 Fnatic VS Spirit第一局
2016/02/27 DOTA
python使用xlrd与xlwt对excel的读写和格式设定
2017/01/21 Python
python SSH模块登录,远程机执行shell命令实例解析
2018/01/12 Python
python matplotlib绘图,修改坐标轴刻度为文字的实例
2018/05/25 Python
利用Python写一个爬妹子的爬虫
2018/06/08 Python
解决python3 urllib 链接中有中文的问题
2018/07/16 Python
Django使用消息提示简单的弹出个对话框实例
2019/11/15 Python
python GUI库图形界面开发之PyQt5控件QTableWidget详细使用方法与属性
2020/02/25 Python
Python图片处理模块PIL操作方法(pillow)
2020/04/07 Python
Python爬虫自动化爬取b站实时弹幕实例方法
2021/01/26 Python
python中openpyxl和xlsxwriter对Excel的操作方法
2021/03/01 Python
加拿大便宜的隐形眼镜商店:Clearly
2016/09/15 全球购物
美国高品质个性化珠宝销售网站:Jewlr
2018/05/03 全球购物
节约能源标语
2014/06/17 职场文书
5s标语大全
2014/06/23 职场文书
先进工作者个人总结
2015/02/15 职场文书
2015年学校教育教学工作总结
2015/04/22 职场文书
反邪教学习心得体会
2016/01/15 职场文书
基于Python绘制子图及子图刻度的变换等的问题
2021/05/23 Python