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

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,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,'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,testA.txt closed? False 
You see the differents,the resource in subthread may not released with setDaemon() 

总结

以上就是本文关于Python线程创建和终止实例代码的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用OpenCV实现视频去抖 整体步骤: 设置输入输出视频 寻找帧之间的移动:使用opencv的特征检测器,检测前一帧的特征,并使用Lucas-Kanade光流算法在下一帧跟踪这些特征,根据两组点,将前一个坐标系映射到当前坐标系完成刚性(欧几里得)变换,最后使用数组纪录帧之间的运动。 计算帧之间的平
前言 对中文标题使用余弦相似度算法和编辑距离相似度分析进行相似度分析。 准备数据集part1 本次使用的数据集来源于前几年的硕士学位论文,可根据实际需要更换。结构如下所示: 学位论文题名 基于卷积神经网络的人脸识别研究 P2P流媒体视频点播系统设计和研究 校园网安全体系的设计与实现 无线传感器网络中
前言 之前尝试写过一个爬虫,那时对网页请求还不够熟练,用的原理是:爬取整个html文件,然后根据标签页筛选有效信息。 现在看来这种方式无疑是吃力不讨好,因此现在重新写了一个爬取天气的程序。 准备工作 网上能轻松找到的是 101010100 北京这种编号,而查看中国气象局URL,他们使用的是北京545
前言 本文使用Python实现了PCA算法,并使用ORL人脸数据集进行了测试并输出特征脸,简单实现了人脸识别的功能。 1. 准备 ORL人脸数据集共包含40个不同人的400张图像,是在1992年4月至1994年4月期间由英国剑桥的Olivetti研究实验室创建。此数据集包含40个类,每个类含10张图
前言 使用opencv对图像进行操作,要求:(1)定位银行票据的四条边,然后旋正。(2)根据版面分析,分割出小写金额区域。 图像校正 首先是对图像的校正 读取图片 对图片二值化 进行边缘检测 对边缘的进行霍夫曼变换 将变换结果从极坐标空间投影到笛卡尔坐标得到倾斜角 根据倾斜角对主体校正 import
天气预报API 功能 从中国天气网抓取数据返回1-7天的天气数据,包括: 日期 天气 温度 风力 风向 def get_weather(city): 入参: 城市名,type为字符串,如西安、北京,因为数据引用中国气象网,因此只支持中国城市 返回: 1、列表,包括1-7的天气数据,每一天的分别为一个
数据来源:House Prices - Advanced Regression Techniques 参考文献: Comprehensive data exploration with Python 1. 导入数据 import pandas as pd import warnings warnin
同步和异步 同步和异步是指程序的执行方式。在同步执行中,程序会按顺序一个接一个地执行任务,直到当前任务完成。而在异步执行中,程序会在等待当前任务完成的同时,执行其他任务。 同步执行意味着程序会阻塞,等待任务完成,而异步执行则意味着程序不会阻塞,可以同时执行多个任务。 同步和异步的选择取决于你的程序需
实现代码 import time import pydirectinput import keyboard if __name__ == &#39;__main__&#39;: revolve = False while True: time.sleep(0.1) if keyboard.is_pr
本文从多个角度分析了vi编辑器保存退出命令。我们介绍了保存和退出vi编辑器的命令,以及如何撤销更改、移动光标、查找和替换文本等实用命令。希望这些技巧能帮助你更好地使用vi编辑器。
Python中的回车和换行是计算机中文本处理中的两个重要概念,它们在代码编写中扮演着非常重要的角色。本文从多个角度分析了Python中的回车和换行,包括回车和换行的概念、使用方法、使用场景和注意事项。通过本文的介绍,读者可以更好地理解和掌握Python中的回车和换行,从而编写出更加高效和规范的Python代码。
SQL Server启动不了错误1067是一种比较常见的故障,主要原因是数据库服务启动失败、权限不足和数据库文件损坏等。要解决这个问题,我们需要检查服务日志、重启服务器、检查文件权限和恢复数据库文件等。在日常的数据库运维工作中,我们应该时刻关注数据库的运行状况,及时发现并解决问题,以确保数据库的正常运行。
信息模块是一种可重复使用的、可编程的、可扩展的、可维护的、可测试的、可重构的软件组件。信息模块的端接需要从接口设计、数据格式、消息传递、函数调用等方面进行考虑。信息模块的端接需要满足高内聚、低耦合的原则,以保证系统的可扩展性和可维护性。
本文从电脑配置、PyCharm版本、Java版本、配置文件以及程序冲突等多个角度分析了Win10启动不了PyCharm的可能原因,并提供了解决方法。
本文主要从多个角度分析了安装SQL Server 2012时可能出现的错误,并提供了解决方法。
Pycharm是一款非常优秀的Python集成开发环境,它可以让Python开发者更加高效地进行代码编写、调试和测试。在Pycharm中设置解释器非常简单,我们可以通过创建新项目、修改项目解释器、设置全局解释器等多种方式进行设置。
Python中有多种方法可以将字符串转换为整数,包括使用int()函数、try-except语句、正则表达式、map()函数、ord()函数和reduce()函数。在实际应用中,应根据具体情况选择最合适的方法。
本文介绍了导入CSV文件的多种方法,包括使用Excel、Python和R等工具。同时,还介绍了导入CSV文件时需要注意的一些细节和问题。CSV文件是数据处理和分析中不可或缺的一部分,希望本文能够对读者有所帮助。
mongodb是一种新型的数据库,它采用了面向文档的数据模型,具有灵活性、高性能和高可用性等优势。但是,mongodb也存在数据结构混乱、安全性和学习成本高等问题。
当Python运行不了时,我们应该从代码、Python环境、操作系统和硬件设备等多个角度来排查问题,并采取相应的解决措施。