Python线程创建和终止实例代码
python主要是通过thread和threading这两个模块来实现多线程支持。
python的thread模块是比較底层的模块,python的threading模块是对thread做了一些封装,能够更加方便的被使用。可是python(cpython)因为GIL的存在无法使用threading充分利用CPU资源,假设想充分发挥多核CPU的计算能力须要使用multiprocessing模块(Windows下使用会有诸多问题)。
假设在对线程应用有较高的要求时能够考虑使用StacklessPython来完毕。StacklessPython是Python的一个改动版本号,对多线程编程有更好的支持,提供了对微线程的支持。微线程是轻量级的线程,在多个线程间切换所需的时间很多其它,占用资源也更少。
通过threading模块创建新的线程有两种方法:一种是通过threading.Thread(Target=executableMethod)-即传递给Thread对象一个可运行方法(或对象);另外一种是继承threading.Thread定义子类并重写run()方法。另外一种方法中,唯一必须重写的方法是run(),可依据需要决定是否重写__init__()。值得注意的是,若要重写__init__(),父类的__init__()必需要在函数第一行调用,否则会触发错误“AssertionError:Thread.__init__()notcalled”
Pythonthreading模块不同于其它语言之处在于它没有提供线程的终止方法,通过Pythonthreading.Thread()启动的线程彼此是独立的。若在线程A中启动了线程B,那么A、B是彼此独立执行的线程。若想终止线程A的同一时候强力终止线程B。一个简单的方法是通过在线程A中调用B.setDaemon(True)实现。
但这样带来的问题是:线程B中的资源(打开的文件、传输数据等)可能会没有正确的释放。所以setDaemon()并不是一个好方法,更为妥当的方式是通过Event机制。以下这段程序体现了setDaemon()和Event机制终止子线程的差别。
importthreading
importtime
classmythread(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
defEventrun(self):
whilenotself.stopevt.isSet():
printself.name+'alive\n'
time.sleep(2)
ifself.File:
print'closeopenedfilein'+self.name+'\n'
self.File.close()
printself.name+'stoped\n'
defDaemonrun(self):
D=mythreadDaemon(self.File)
D.setDaemon(True)
whilenotself.stopevt.isSet():
printself.name+'alive\n'
time.sleep(2)
printself.name+'stoped\n'
defrun(self):
ifself.Type=='event':self.Eventrun()
else:self.Daemonrun()
classmythreadDaemon(threading.Thread):
def__init__(self,File=None,name='Daemonthread'):
threading.Thread.__init__(self)
self.name=name
self.File=File
defrun(self):
whileTrue:
printself.name+'alive\n'
time.sleep(2)
ifself.File:
print'closeopenedfilein'+self.name+'\n'
self.File.close()
printself.name+'stoped\n'
defevtstop():
stopevt=threading.Event()
FileA=open('testA.txt','w')
FileB=open('testB.txt','w')
A=mythread(stopevt,FileA,'subthreadA')
B=mythread(stopevt,FileB,'subthreadB')
printrepr(threading.currentThread())+'alive\n'
printFileA.name+'closed?
'+repr(FileA.closed)+'\n'
printFileB.name+'closed?'+repr(FileB.closed)+'\n'
A.start()
B.start()
time.sleep(1)
printrepr(threading.currentThread())+'sendstopsignal\n'
stopevt.set()
A.join()
B.join()
printrepr(threading.currentThread())+'stoped\n'
print'afterAstoped,'+FileA.name+'closed?'+repr(FileA.closed)+'\n'
print'afterAstoped,'+FileB.name+'closed?
'+repr(FileB.closed)+'\n'
defdaemonstop():
stopevt=threading.Event()
FileA=open('testA.txt','r')
A=mythread(stopevt,FileA,'subthreadA',Type='Daemon')
printrepr(threading.currentThread())+'alive\n'
printFileA.name+'closed?
'+repr(FileA.closed)+'\n'
A.start()
time.sleep(1)
stopevt.set()
A.join()
printrepr(threading.currentThread())+'stoped\n'
print'afterAstoped,'+FileA.name+'closed?'+repr(FileA.closed)+'\n'
ifnotFileA.closed:
print'Youseethedifferents,theresourceinsubthreadmaynotreleasedwithsetDaemon()'
FileA.close()
if__name__=='__main__':
print'-------stopsubthreadexamplewithEvent:----------\n'
evtstop()
print'-------Daemonstopsubthreadexample:----------\n'
daemonstop()
执行结果是:
-------stopsubthreadexamplewithEvent:---------- <_MainThread(MainThread,started2436)>alive testA.txtclosed? False testB.txtclosed?False subthreadAalive subthreadBalive <_MainThread(MainThread,started2436)>sendstopsignal closeopenedfileinsubthreadA closeopenedfileinsubthreadB subthreadAstoped subthreadBstoped <_MainThread(MainThread,started2436)>stoped afterAstoped,testA.txtclosed?True afterAstoped,testB.txtclosed? True -------Daemonstopsubthreadexample:---------- <_MainThread(MainThread,started2436)>alive testA.txtclosed? False subthreadAalive subthreadAstoped <_MainThread(MainThread,started2436)>stoped afterAstoped,testA.txtclosed?False Youseethedifferents,theresourceinsubthreadmaynotreleasedwithsetDaemon()
总结
以上就是本文关于Python线程创建和终止实例代码的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!