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


猜你喜欢
- 本文实例讲述了PHP排序算法之冒泡排序(Bubble Sort)实现方法。分享给大家供大家参考,具体如下:基本思想:冒泡排序是一种交换排序,
- Oracle数据库出现死锁的时候可以按照以下处理步骤加以解决:第一步:尝试在sqlplus中通过sql命令进行删除,如果能够删除成功,则万事
- 说下整体思路1、服务器安装ffmpeg2、使用ffmpeg -i 指令来转换amr为mp3格式(这个到时候写在PHP代码中,使用exec函数
- 随机背景--当你每次进入该页面时,从已指定的图片文件夹中,随机选取一个图片作为背景显示。这里介绍的方法是用ASP+CSS来实现的。 &nbs
- 本文实例讲述了Python使用中文正则表达式匹配指定中文字符串的方法。分享给大家供大家参考,具体如下:业务场景:从中文字句中匹配出指定的中文
- 本文实例为大家分享了Python飞机大战项目,供大家参考,具体内容如下import gcimport randomimport pygame
- 表单内有两个提交按钮,要实现当点击不同的提交按钮时,分别进行两个不同的处理过程,在这里有实现表单多按钮提交action的处理方法分享给大家。
- 环境系统:win10cpu:i7-6700HQgpu:gtx965mpython : 3.6pytorch :0.3数据下载来源自Sasan
- 通过这个布局思路来做一个简单的后台管理系统也是OK的,大家可以参考一下啦!话不多说,还是先来梳理一下需要的第三方模块。PyQ5 的UI界面布
- 熟悉web开发的同学对hook钩子肯定不陌生,通过钩子可以方便的实现一些触发和回调,并且做一些过滤和拦截。django中的中间件(middl
- TCP客户端程序开发1. 开发 TCP 客户端程序开发步骤回顾创建客户端套接字对象和服务端套接字建立连接发送数据接收数据关闭客户端套接字2.
- JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,它使得人们很容易的进行阅读和编写。同时也方便了机
- 当我想要完美的使用:nth-child或者:nth-of-type的时候有点儿头晕。你越理解它们,就能写出越好的CSS规则!在这些简单的”秘
- 1.生成器# 一边循环一边计算的机制,称为生成器:generator;# 创建generator方法:# 1.把一个列表生成式的[]改成()
- if语句>>通用格式if语句一般形式如下:if <test1>: <statements1>elif &
- 如果你是个学生,你应该会C,C++和Java。还会一些VB,或C#/.NET。多少你还可能开发过一些Web网页,你知道一些HTML,CSS和
- 大家好,并发编程 今天开始进入第二篇。今天的内容会比较基础,主要是为了让新手也能无障碍地阅读,所以还是要再巩固下基础。学完了基础,你们也就能
- 一般调试程序的时候都比较倾向print,利用直接打印的方法作出判断,但是print只能打印出结果,对类型无法作出判断。例如:复制代码a =
- Vue 路由传参加密首先,创建一个base64.jsconst Base64 = { //加密 en
- 本文实例讲述了Python+Socket实现基于TCP协议的客户与服务端中文自动回复聊天功能。分享给大家供大家参考,具体如下:【吐槽】网上的