stop subthread example with Event
来源:互联网 发布:teambition 类似软件 编辑:程序博客网 时间:2024/05/16 19:03
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
0 0
- stop subthread example with Event
- start-stop-daemon example
- start-stop-daemon example
- An keypress event example
- HTK Example: Acoustic Event Detection
- Example Program: Event-Driven Simulation
- mysql binlog事件 Rotate Event和Stop
- WSDL explaination with example
- AngularJS with Cookies Example
- Example: Receiving Event Notifications Through WMI
- Example #1: Struts with Hibernate
- coding with a simple example
- “Hello World” Example with AspectDNG
- symbian Database Example with Navigation
- mocking webservice with SoapUI example
- JSON Example With Jersey + Jackson
- JSON Example With RESTEasy + Jackson
- Apache Camel with SQL Example
- 七牛evm云主机完整安装ffmpeg
- oracle 查询表字段明显、字段注释、表注释
- 使用Jsoup解析Html == TextView显示html图片的方法
- Spring源码阅读 --BeanDefinition
- 互动教程 for Excel 2016
- stop subthread example with Event
- FusionCharts 3.2 使用说明 以及 swf
- 郑轻OJ 1205: 你爱我么?
- Device Tree Customization (转)
- 浅谈C#中常见的委托
- 完全卸载oracle11g步骤
- MySQL存储引擎engine=innodb和engine=myisam的区别
- java实现 阿拉伯数字转换为汉字数字 算法
- 线程同步--关键段CRITICAL_SECTION