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基础教程
Feb 05 Python
分享给Python新手们的几道简单练习题
Sep 21 Python
python2.x实现人民币转大写人民币
Jun 20 Python
Python实现注册、登录小程序功能
Sep 21 Python
python实现图片识别汽车功能
Nov 30 Python
pandas求两个表格不相交的集合方法
Dec 08 Python
python实现求特征选择的信息增益
Dec 18 Python
python傅里叶变换FFT绘制频谱图
Jul 19 Python
pytorch多进程加速及代码优化方法
Aug 19 Python
Python使用Pandas读写Excel实例解析
Nov 19 Python
Python AutoCAD 系统设置的实现方法
Apr 01 Python
基于Python爬虫采集天气网实时信息
Jun 05 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
Valerio 发布了 Mootools
2006/09/23 Javascript
JavaScript confirm选择判断
2008/10/18 Javascript
JavaScript 学习历程和心得分享
2010/12/12 Javascript
Javascript/Jquery——简单定时器的多种实现方法
2013/07/03 Javascript
学习vue.js计算属性
2016/12/03 Javascript
Bootstrap学习笔记之进度条、媒体对象实例详解
2017/03/09 Javascript
react.js 父子组件数据绑定实时通讯的示例代码
2017/09/25 Javascript
Nodejs实现爬虫抓取数据实例解析
2018/07/05 NodeJs
使用Javascript简单计算器
2018/11/17 Javascript
详解ECMAScript2019/ES10新属性
2019/12/06 Javascript
ant design vue 表格table 默认勾选几项的操作
2020/10/31 Javascript
[04:54]DOTA2-DPC中国联赛1月31日Recap集锦
2021/03/11 DOTA
python错误处理详解
2014/09/28 Python
Python random模块常用方法
2014/11/03 Python
Python中函数的参数定义和可变参数用法实例分析
2015/06/04 Python
Python使用redis pool的一种单例实现方式
2016/04/16 Python
python算法表示概念扫盲教程
2017/04/13 Python
Python实现将MySQL数据库表中的数据导出生成csv格式文件的方法
2018/01/11 Python
python的socket编程入门
2018/01/29 Python
python字典快速保存于读取的方法
2018/03/23 Python
python+OpenCV实现车牌号码识别
2019/11/08 Python
tensorflow estimator 使用hook实现finetune方式
2020/01/21 Python
Python 发送邮件方法总结
2020/08/10 Python
如何用Python提取10000份log中的产品信息
2021/01/14 Python
乌克兰品牌化妆品和香水在线商店:Bomond
2020/01/14 全球购物
综合办公室主任岗位职责
2014/04/13 职场文书
竞聘演讲稿
2014/04/24 职场文书
车间安全生产标语
2014/06/06 职场文书
入党现实表现材料
2014/12/23 职场文书
大学生自荐信怎么写
2015/03/26 职场文书
党员承诺书格式范文
2015/04/28 职场文书
餐饮服务食品安全承诺书
2015/04/29 职场文书
2015年乡镇组织委员工作总结
2015/10/23 职场文书
MySQL性能压力基准测试工具sysbench的使用简介
2021/04/21 MySQL
分析SQL窗口函数之取值窗口函数
2022/04/21 Oracle
Vue2项目中对百度地图的封装使用详解
2022/06/16 Vue.js