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模型中的字段和model名显示为中文小技巧分享
Nov 18 Python
Python简单进程锁代码实例
Apr 27 Python
python执行get提交的方法
Apr 29 Python
Python numpy中矩阵的基本用法汇总
Feb 12 Python
python实现吃苹果小游戏
Mar 21 Python
Django自关联实现多级联动查询实例
May 19 Python
python可以用哪些数据库
Jun 22 Python
django Model层常用验证器及自定义验证器详解
Jul 15 Python
openCV提取图像中的矩形区域
Jul 21 Python
Python3爬虫中关于中文分词的详解
Jul 29 Python
Django如何继承AbstractUser扩展字段
Nov 27 Python
Pytorch实现图像识别之数字识别(附详细注释)
May 11 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 header 跳转
2013/06/17 PHP
php实现生成验证码实例分享
2016/04/10 PHP
one.php 多项目、函数库、类库 统一为一个版本的方法
2020/08/24 PHP
syntaxhighlighter 使用方法
2007/07/02 Javascript
JS 去除Array中的null值示例代码
2013/11/20 Javascript
js处理php输出时间戳对不上号的解决方法
2014/06/20 Javascript
jQuery实现按钮只点击一次后就取消点击事件绑定的方法
2015/06/26 Javascript
jQuery取消特定的click事件
2016/02/29 Javascript
无需 Flash 使用 jQuery 复制文字到剪贴板
2016/04/26 Javascript
echarts3 使用总结(绘制各种图表,地图)
2017/01/05 Javascript
简单谈谈axios中的get,post方法
2017/06/25 Javascript
vue中使用sessionStorage记住密码功能
2018/07/24 Javascript
了解JavaScript中let语句
2019/05/30 Javascript
JS面向对象编程基础篇(一) 对象和构造函数实例详解
2020/03/03 Javascript
ES2020让代码更优美的运算符 (?.) (??)
2021/01/04 Javascript
[41:37]DOTA2北京网鱼队选拔赛——冲击职业之路
2015/04/13 DOTA
python批量生成本地ip地址的方法
2015/03/23 Python
Python callable()函数用法实例分析
2018/03/17 Python
python中利用h5py模块读取h5文件中的主键方法
2018/06/05 Python
对python函数签名的方法详解
2019/01/22 Python
python f-string式格式化听语音流程讲解
2019/06/18 Python
python二元表达式用法
2019/12/04 Python
python tkinter之顶层菜单、弹出菜单实例
2020/03/04 Python
Pytest如何使用skip跳过执行测试
2020/08/13 Python
用 Django 开发一个 Python Web API的方法步骤
2020/12/03 Python
Joe Fresh官网:加拿大时尚品牌和零售连锁店
2016/11/30 全球购物
Zavvi西班牙:电子游戏、极客服装、Blu-ray、Funko Pop等
2019/05/03 全球购物
德国足球商店:OUTFITTER
2019/05/06 全球购物
预订旅游活动、景点和旅游:GetYourGuide
2019/09/29 全球购物
工作失误检讨书范文大全
2014/01/13 职场文书
社区禁毒工作方案
2014/06/02 职场文书
县人大领导班子四风对照检查材料思想汇报
2014/10/09 职场文书
2016公司年会通知范文
2015/04/25 职场文书
考勤制度通知
2015/04/25 职场文书
美丽人生观后感
2015/06/03 职场文书
2019销售早会主持词
2019/06/27 职场文书