python杀死一个线程的方法
最近在项目中遇到这一需求:
我需要一个函数工作,比如远程连接一个端口,远程读取文件等,但是我给的时间有限,比如,4秒钟如果你还没有读取完成或者连接成功,我就不等了,很可能对方已经宕机或者拒绝了。这样可以批量做一些事情而不需要一直等,浪费时间。
结合我的需求,我想到这种办法:
1、在主进程执行,调用一个进程执行函数,然后主进程sleep,等时间到了,就kill执行函数的进程。
测试一个例子:
importtime importthreading defp(i): printi classtask(threading.Thread): def__init__(self,fun,i): threading.Thread.__init__(self) self.fun=fun self.i=i self.thread_stop=False defrun(self): whilenotself.thread_stop: self.fun(self.i) defstop(self): self.thread_stop=True deftest(): thread1=task(p,2) thread1.start() time.sleep(4) thread1.stop() return if__name__=='__main__': test()
经过测试只定了4秒钟。
经过我的一番折腾,想到了join函数,这个函数式用来等待一个线程结束的,如果这个函数没有结束的话,那么,就会阻塞当前运行的程序。关键是,这个参数有一个可选参数:join([timeout]): 阻塞当前上下文环境的线程,直到调用此方法的线程终止或到达指定的timeout(可选参数)。
不多说了贴下面代码大家看下:
#!/usr/bin/envpython #-*-coding:utf-8-*- ''''' author:cogbee time:2014-6-13 function:readme ''' importpdb importtime importthreading importos #pdb.set_trace() classtask(threading.Thread): def__init__(self,ip): threading.Thread.__init__(self) self.ip=ip self.thread_stop=False defrun(self): whilenotself.thread_stop: #//添加你要做的事情,如果成功了就设置一下<spanstyle="font-family:Arial,Helvetica,sans-serif;">self.thread_stop变量。</span> [python]viewplaincopy在CODE上查看代码片派生到我的代码片 iffile!='': self.thread_stop=True defstop(self): self.thread_stop=True deftest(eachline): globalfile list=[] foripineachline: thread1=task(ip) thread1.start() thread1.join(3) ifthread1.isAlive(): thread1.stop() continue #将可以读取的都存起来 iffile!='': list.append(ip) printlist if__name__=='__main__': eachline=['1.1.1.1','222.73.5.54'] test(eachline)
下面给大家分享我写的一段杀死线程的代码。
由于python线程没有提供abort方法,分享下面一段代码杀死线程:
importthreading
importinspect
importctypes
def_async_raise(tid,exctype):
"""raisestheexception,performscleanupifneeded"""
ifnotinspect.isclass(exctype):
raiseTypeError("Onlytypescanberaised(notinstances)")
res=ctypes.pythonapi.PyThreadState_SetAsyncExc(tid,ctypes.py_object(exctype))
ifres==0:
raiseValueError("invalidthreadid")
elifres!=1:
#"""ifitreturnsanumbergreaterthanone,you'reintrouble,
#andyoushouldcallitagainwithexc=NULLtoreverttheeffect"""
ctypes.pythonapi.PyThreadState_SetAsyncExc(tid,0)
raiseSystemError("PyThreadState_SetAsyncExcfailed")
classThread(threading.Thread):
def_get_my_tid(self):
"""determinesthis(self's)threadid"""
ifnotself.isAlive():
raisethreading.ThreadError("thethreadisnotactive")
#dowehaveitcached?
ifhasattr(self,"_thread_id"):
returnself._thread_id
#no,lookforitinthe_activedict
fortid,tobjinthreading._active.items():
iftobjisself:
self._thread_id=tid
returntid
raiseAssertionError("couldnotdeterminethethread'sid")
defraise_exc(self,exctype):
"""raisesthegivenexceptiontypeinthecontextofthisthread"""
_async_raise(self._get_my_tid(),exctype)
defterminate(self):
"""raisesSystemExitinthecontextofthegiventhread,whichshould
causethethreadtoexitsilently(unlesscaught)"""
self.raise_exc(SystemExit)
使用例子:
>>>importtime >>>fromthread2importThread >>> >>>deff(): ...try: ...whileTrue: ...time.sleep(0.1) ...finally: ...print"outtahere" ... >>>t=Thread(target=f) >>>t.start() >>>t.isAlive() True >>>t.terminate() >>>t.join() outtahere >>>t.isAlive() False
试了一下,很不错,只是在要kill的线程中如果有time.sleep()时,好像工作不正常,没有找出真正的原因是什么。已经是很强大了。哈哈。