侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

Python线程创建和终止实例代码

Python  /  管理员 发布于 7年前   118

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+matplotlib实现动态绘制图片实例代码(交互式绘图)
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客