Python线程创建和终止实例代码
作者:claireyuancy 发布时间:2022-06-29 11:01:34
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()
来源:https://www.cnblogs.com/claireyuancy/p/6705253.html
![](https://www.aspxhome.com/images/zang.png)
![](https://www.aspxhome.com/images/jiucuo.png)
猜你喜欢
- 目录过程拍照用到的Python 操作库Python遍历文件夹获取图片旋转图片展示方向并压缩像素整体代码整体代码将脚本打包成exe安装&nbs
- 本节列出了可以运行MySQL的操作系统。我们使用GNU Autoconf,因此将MySQL移植到所有使用Posix线程和C++编译器的现代系
- 本文实例讲述了Python面向对象程序设计之私有变量,私有方法原理与用法。分享给大家供大家参考,具体如下:私有变量,私有方法:python的
- 一、数据描述数据集中9994条数据,横跨1237天,销售额为2,297,200.8603美元,利润为286,397.0217美元,他们的库存
- 透视表是一种可以对数据动态排布并且分类汇总的表格格式。对于熟练使用 excel 的伙伴来说,一定很是亲切!pd.pivot_table()
- 相信大家对于常见 CSS BUG 的处理已经相对比较熟悉,例如:IE6 Three Pixel Gap、IE5/6 Doubled Floa
- -- begin auth.inc -- <?php $
- 一、使用ImageFolder读取数据集时忽略特定文件如果事先知道需要忽略哪些文件,当然直接从数据集里删除就行了。但如果需要在程序运行时动态
- 1、说明Tasks用于并发调度协程,通过asyncio.create_task(协程对象)创建Task对象,使协程能够加入事件循环,等待调度
- 研究(2)中讨论了栅格系统的基础知识。这一篇将集中探讨栅格系统的粒度问题。(注:如非特别指明,栅格系统均指24列960栅格系统)淘宝的首页(
- 阅读上一篇:javascript面向对象编程(三)继承是面向对象语言中的一个重要概念,现在我们来探讨一下继承。在网上搜一下javascrip
- 简单的Python代码:用户登录注册利用业余时间,写了一个用户进行登录注册的代码,非常简单。主要实现的功能是:1、可以进行用户登录,在用户进
- 关于这个话题,我也看到网上有其他方法来解决。 不过从性能和代码量上来看,我有更好的办法。 在这里和大家 分享。 原理其实很简单, 知识1、长
- Asp开发 联通CDMA以下是在开发wap中的随笔,其中一些对于“老鸟”来说,谈不上什么,希望对初学者有所帮助,大家有什么小技巧,欢迎顶上来
- 前言favicon.ico是网站的图标也是网站的头像,简单来说,就是让我们的网站更加好看。本文主要给大家介绍了关于优雅处理Django中fa
- 网上的SQL优化的文章实在是很多,说实在的,我也曾经到处找这样的文章,什么不要使用IN了,什么OR了,什么AND了,很多很多,还有很多人拿出
- 本文实例讲述了python使用Flask框架获取用户IP地址的方法。分享给大家供大家参考。具体如下:下面的代码包含了html页面和pytho
- Mysqli是php5之后才有的功能,没有开启扩展的朋友可以打开您的php.ini的配置文件。 查找下面的语句:;extension=php
- 尽管人们期望在屏幕上有些改变,但是CSS和HTML对页面中的交互能做的实在太少了,而那些还需要用代码来实现。比如一个链接要么是这个颜色,要么
- 本文实例为大家分享了JSP使用commons-fileupload实现文件上传代码,供大家参考,具体内容如下1、准备:将commons-fi