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编程中的文件读写及相关的文件对象方法讲解
Jan 19 Python
Python 序列的方法总结
Oct 18 Python
Python实现合并同一个文件夹下所有PDF文件的方法示例
Apr 28 Python
Ubuntu下Python2与Python3的共存问题
Oct 31 Python
解决在Python编辑器pycharm中程序run正常debug错误的问题
Jan 17 Python
python的schedule定时任务模块二次封装方法
Feb 19 Python
python实现接口并发测试脚本
Jun 25 Python
Python基于BeautifulSoup和requests实现的爬虫功能示例
Aug 02 Python
Django 后台获取文件列表 InMemoryUploadedFile的例子
Aug 07 Python
利用python、tensorflow、opencv、pyqt5实现人脸实时签到系统
Sep 25 Python
给大家整理了19个pythonic的编程习惯(小结)
Sep 25 Python
Flask-SocketIO服务端安装及使用代码示例
Nov 26 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结合表单实现一些简单功能的例子
2011/06/04 PHP
PHP中isset与array_key_exists的区别实例分析
2015/06/02 PHP
学习thinkphp5.0验证类使用方法
2017/11/16 PHP
php获取目录下所有文件及目录(多种方法)(推荐)
2019/05/14 PHP
PHP CURL实现模拟登陆并上传文件操作示例
2020/01/02 PHP
PHP利用curl发送HTTP请求的实例代码
2020/07/09 PHP
在IE6下发生Internet Explorer cannot open the Internet site错误
2010/06/21 Javascript
JavaScript DOM 编程艺术(第2版)读书笔记(JavaScript的最佳实践)
2013/10/01 Javascript
javascript中数组的sort()方法的使用介绍
2013/12/18 Javascript
原生JavaScript实现瀑布流布局
2020/06/28 Javascript
JavaScript事件类型中UI事件详解
2016/01/14 Javascript
详解XMLHttpRequest(二)响应属性、二进制数据、监测上传下载进度
2016/09/14 Javascript
Vue.js实现简单ToDoList 前期准备(一)
2016/12/01 Javascript
JavaScript中的子窗口与父窗口的互相调用问题
2017/02/08 Javascript
基于Bootstrap的标签页组件及bootstrap-tab使用说明
2017/07/25 Javascript
详解vue mint-ui源码解析之loadmore组件
2017/10/11 Javascript
解决angular 使用原生拖拽页面卡顿及表单控件输入延迟问题
2020/04/21 Javascript
基于JS实现操作成功之后自动跳转页面
2020/09/25 Javascript
vue 中this.$set 动态绑定数据的案例讲解
2021/01/29 Vue.js
[02:23]DOTA2英雄基础教程 幻影长矛手
2013/12/09 DOTA
[03:22]DAC最前线(第二期)—DOTA2亚洲邀请赛主赛场周边及线路探访
2015/01/24 DOTA
python脚本实现分析dns日志并对受访域名排行
2014/09/18 Python
python调用java模块SmartXLS和jpype修改excel文件的方法
2015/04/28 Python
python利用正则表达式排除集合中字符的功能示例
2017/10/10 Python
python与字符编码问题
2019/05/24 Python
pandas 数据索引与选取的实现方法
2019/06/21 Python
python实现简单坦克大战
2020/03/27 Python
django实现模板中的字符串文字和自动转义
2020/03/31 Python
个人找工作自荐信格式
2013/09/21 职场文书
学校师德师风自我剖析材料
2014/09/29 职场文书
2014年电厂个人工作总结
2014/11/27 职场文书
敬老院义诊活动总结
2015/05/07 职场文书
职工趣味运动会开幕词
2016/03/04 职场文书
奶茶店的创业计划书该怎么写?
2019/07/15 职场文书
python基于scrapy爬取京东笔记本电脑数据并进行简单处理和分析
2021/04/14 Python
Windows Server 2012 R2服务器安装与配置的完整步骤
2022/07/15 Servers