stop subthread example with Event

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值