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之大话题小函数(1)
Oct 10 Python
详解Python的Django框架中manage命令的使用与扩展
Apr 11 Python
Python快速从注释生成文档的方法
Dec 26 Python
Python 读取指定文件夹下的所有图像方法
Apr 27 Python
在python中以相同顺序shuffle两个list的方法
Dec 13 Python
Python实现监控Nginx配置文件的不同并发送邮件报警功能示例
Feb 26 Python
Python基础学习之时间转换函数用法详解
Jun 18 Python
Python处理时间日期坐标轴过程详解
Jun 25 Python
django mysql数据库及图片上传接口详解
Jul 18 Python
Python selenium的基本使用方法分析
Dec 21 Python
Python Pillow.Image 图像保存和参数选择方式
Jan 09 Python
Python中random模块常用方法的使用教程
Oct 04 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
PHPMailer邮件发送的实现代码
2013/05/04 PHP
PHP中isset()和unset()函数的用法小结
2014/03/11 PHP
WordPress中访客登陆实现邮件提醒的PHP脚本实例分享
2015/12/14 PHP
YiiFramework入门知识点总结(图文教程)
2015/12/28 PHP
PHP递归遍历多维数组实现无限分类的方法
2016/05/06 PHP
Yii2汉字转拼音类的实例代码
2017/04/18 PHP
tp5框架基于ajax实现异步删除图片的方法示例
2020/02/10 PHP
javascript 面向对象继承
2009/11/26 Javascript
JavaScript XML和string相互转化实现代码
2011/07/04 Javascript
cnblogs 代码高亮显示后的代码复制问题解决实现代码
2011/12/14 Javascript
jquery下checked取值问题的解决方法
2012/08/09 Javascript
jQuery图片播放8款精美插件分享
2013/02/17 Javascript
Javascript实现多彩雪花从天降散落效果的方法
2015/02/02 Javascript
Bootstrap树形组件jqTree的简单封装
2016/01/25 Javascript
JavaScript实现隐藏省略文字效果的方法
2017/04/27 Javascript
JS中的三个循环小结
2017/06/20 Javascript
layui实现checkbox的目录树tree的例子
2019/09/12 Javascript
angular inputNumber指令输入框只能输入数字的实现
2019/12/03 Javascript
javascript设计模式 ? 组合模式原理与应用实例分析
2020/04/14 Javascript
Python with的用法
2014/08/22 Python
python简单分割文件的方法
2015/07/30 Python
Python中的pack和unpack的使用
2018/03/12 Python
浅谈Pandas 排序之后索引的问题
2018/06/07 Python
Python并发之多进程的方法实例代码
2018/08/15 Python
Python转换时间的图文方法
2019/07/01 Python
python中数据库like模糊查询方式
2020/03/02 Python
python怎么自定义捕获错误
2020/06/29 Python
请写出一段Python代码实现删除一个list里面的重复元素
2015/12/29 面试题
成人大专生实习期的自我评价
2013/10/02 职场文书
数学与统计学院学生个人职业生涯规划书
2014/02/10 职场文书
水电维修专业推荐信
2014/09/06 职场文书
奉献家乡演讲稿
2014/09/13 职场文书
农村党支部书记四风问题个人对照检查材料
2014/09/21 职场文书
汽车转让协议书范本
2014/12/07 职场文书
校长一岗双责责任书
2015/05/09 职场文书
公务员学习中国梦心得体会
2016/01/05 职场文书