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 相关文章推荐
Django imgareaselect手动剪切头像实现方法
May 26 Python
Python输出汉字字库及将文字转换为图片的方法
Jun 04 Python
Python基于matplotlib实现绘制三维图形功能示例
Jan 18 Python
python控制windows剪贴板,向剪贴板中写入图片的实例
May 31 Python
Python Tkinter模块实现时钟功能应用示例
Jul 23 Python
python爬虫之自动登录与验证码识别
Jun 15 Python
python list格式数据excel导出方法
Oct 31 Python
Python_查看sqlite3表结构,查询语句的示例代码
Jul 17 Python
Python Django实现layui风格+django分页功能的例子
Aug 29 Python
python 变量初始化空列表的例子
Nov 28 Python
Python爬虫自动化获取华图和粉笔网站的错题(推荐)
Jan 08 Python
python 开心网和豆瓣日记爬取的小爬虫
May 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源代码数组统计count分析
2011/08/02 PHP
php接口和抽象类使用示例详解
2014/03/02 PHP
PHP调试函数和日志记录函数分享
2015/01/31 PHP
php中使用array_filter()函数过滤数组实例讲解
2021/03/03 PHP
javascript 随机展示头像实现代码
2011/12/06 Javascript
解析ScrollPic在ie8下只滚动一遍,然后变为空白 ie6,ie7,chrome,firefox正常
2013/06/26 Javascript
jquery.mousewheel实现整屏翻屏效果
2015/08/30 Javascript
JS实现为排序好的字符串找出重复行的方法
2016/03/02 Javascript
深入理解JQuery循环绑定事件
2016/06/02 Javascript
javascirpt实现2个iframe之间传值的方法
2016/06/30 Javascript
利用jquery获取select下拉框的值
2016/11/23 Javascript
微信小程序 picker-view 组件详解及简单实例
2017/01/10 Javascript
微信小程序商城项目之侧栏分类效果(1)
2017/04/17 Javascript
JS实现标签页切换效果
2017/05/04 Javascript
jsonp跨域获取数据的基础教程
2018/07/01 Javascript
Phaser.js实现简单的跑酷游戏附源码下载
2018/10/26 Javascript
vue中nextTick用法实例
2019/09/11 Javascript
VUE : vue-cli中去掉路由中的井号#操作
2020/09/04 Javascript
Python使用win32com实现的模拟浏览器功能示例
2017/07/13 Python
Python模拟脉冲星伪信号频率实例代码
2018/01/03 Python
Pandas之Dropna滤除缺失数据的实现方法
2019/06/25 Python
python下PyGame的下载与安装过程及遇到问题
2019/08/04 Python
Python socket非阻塞模块应用示例
2019/09/12 Python
python设置代理和添加镜像源的方法
2020/02/14 Python
Python读写操作csv和excle文件代码实例
2020/03/16 Python
美国孕妇装品牌:Destination Maternity
2018/02/04 全球购物
德国童装购物网站:NICKI´S.com
2018/04/20 全球购物
美国运动鞋类和服装零售连锁店:Shoe Palace
2019/08/13 全球购物
英国时尚泳装品牌:Maru Swimwear
2019/10/06 全球购物
大学生个人求职信范文
2013/09/21 职场文书
自荐信的基本格式
2014/02/22 职场文书
企业厂务公开实施方案
2014/03/26 职场文书
初中作文评语大全
2014/04/23 职场文书
环保倡议书500字
2014/05/15 职场文书
恰同学少年观后感
2015/06/08 职场文书
2016大学生就业指导课心得体会
2016/01/15 职场文书