Background
Python threading模块不同于其他语言之处在于它没有提供线程的终止方法,通过Python threading.Thread()启动的线程彼此是独立的,启动了线程B,B是独立运行的线程。若想终止线程的同时强力终止线程B,更为妥当的方式是通过Event机制, 线程中的资源(打开的文件、数据传输等)可正确的释放。
code
#-*-coding:utf-8-*-
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 eeee\n'
#time.sleep(2)
print "I am here, stupid !"
if self.File:
print 'close opened file in '+self.name'\n'
self.File.close()
print self.name +' stoped eeee\n'
def run(self):
self.Eventrun()
def eventstop():
stopevt = threading.Event()
FileA = open('testA.txt','w')
A = mythread(stopevt,FileA,'subthreadA')
print repr(threading.currentThread())+'alive\n'
print FileA.name + ' closed? '+repr(FileA.closed)+'\n'
A.start()
print repr(threading.currentThread())+'send stop signal\n'
#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 __name__ =='__main__':
print '-------stop subthread example with Event:----------\n'
eventstop()
Test result :
-------stop subthread example with Event:----------
<_MainThread(MainThread, started 140735271691008)>alive
testA.txt closed? False
subthreadA alive eeee
subthreadA alive eeee
subthreadA alive eeee
subthreadA alive eeee
subthreadA alive eeee
subthreadA alive eeee
subthreadA alive eeee
subthreadA alive eeee
subthreadA alive eeee
<_MainThread(MainThread, started 140735271691008)>send stop signal
I am here, stupid !
close opened file in subthreadA
subthreadA stoped eeee
<_MainThread(MainThread, started 140735271691008)>stoped
after A stoped, testA.txt closed? True