資訊內(nèi)容
python如何終止線程前言 · 零解決方案 · 壹解決方案 · 貳解決方案 · 叁
python終止線程的方法:1、調(diào)用stop函數(shù),并使用join函數(shù)來(lái)等待線程合適地退出;2、在python線程里面raise一個(gè)Exception;3、用“thread.join”方式結(jié)束線程。r4P少兒編程網(wǎng)-https://www.pxcodes.com
r4P少兒編程網(wǎng)-https://www.pxcodes.com
本文操作環(huán)境:windows7系統(tǒng)、python3.5版,DELL G3電腦。r4P少兒編程網(wǎng)-https://www.pxcodes.com
前言 · 零我們知道,在python里面要終止一個(gè)線程,常規(guī)的做法就是設(shè)置/檢查 --->標(biāo)志或者鎖方式來(lái)實(shí)現(xiàn)的。r4P少兒編程網(wǎng)-https://www.pxcodes.com
這種方式好不好呢?r4P少兒編程網(wǎng)-https://www.pxcodes.com
應(yīng)該是不大好的!因?yàn)樵谒械某绦蛘Z(yǔ)言里面,突然地終止一個(gè)線程,這無(wú)論如何都不是一個(gè)好的設(shè)計(jì)模式。r4P少兒編程網(wǎng)-https://www.pxcodes.com
同時(shí)r4P少兒編程網(wǎng)-https://www.pxcodes.com
有些情況下更甚,比如:r4P少兒編程網(wǎng)-https://www.pxcodes.com
線程打開(kāi)一個(gè)必須合理關(guān)閉的臨界資源時(shí),比如打開(kāi)一個(gè)可讀可寫(xiě)的文件;線程已經(jīng)創(chuàng)建了好幾個(gè)其他的線程,這些線程也是需要被關(guān)閉的(這可存在子孫線程游離的風(fēng)險(xiǎn)啊!)。簡(jiǎn)單來(lái)說(shuō),就是我們一大群的線程共線了公共資源,你要其中一個(gè)線程“離場(chǎng)”,假如這個(gè)線程剛好占用著資源,那么強(qiáng)制讓其離開(kāi)的結(jié)局就是資源被鎖死了,大家都拿不到了!怎么樣是不是有點(diǎn)類似修仙類小說(shuō)的情節(jié)!r4P少兒編程網(wǎng)-https://www.pxcodes.com
知道為啥threading僅有start而沒(méi)有end不?r4P少兒編程網(wǎng)-https://www.pxcodes.com
你看,線程一般用在網(wǎng)絡(luò)連接、釋放系統(tǒng)資源、dump流文件,這些都跟IO相關(guān)了,你突然關(guān)閉線程那這些
沒(méi)有合理地關(guān)閉怎么辦?是不是就是給自己造bug呢?啊?!r4P少兒編程網(wǎng)-https://www.pxcodes.com
因此這種事情中**重要的不是終止線程而是線程的清理啊。r4P少兒編程網(wǎng)-https://www.pxcodes.com
解決方案 · 壹一個(gè)比較nice的方式就是每個(gè)線程都帶一個(gè)退出請(qǐng)求標(biāo)志,在線程里面間隔一定的時(shí)間來(lái)檢查一次,看是不是該自己離開(kāi)了!r4P少兒編程網(wǎng)-https://www.pxcodes.com
import threading class StoppableThread(threading.Thread): """Thread class with a stop() method. The thread itself has to check regularly for the stopped() condition.""" def __init__(self): super(StoppableThread, self).__init__() self._stop_event = threading.Event() def stop(self): self._stop_event.set() def stopped(self): return self._stop_event.is_set()在這部分代碼所示,當(dāng)你想要退出線程的時(shí)候你應(yīng)當(dāng)顯示調(diào)用stop()函數(shù),并且使用join()函數(shù)來(lái)等待線程合適地退出。線程應(yīng)當(dāng)周期性地檢測(cè)停止標(biāo)志。r4P少兒編程網(wǎng)-https://www.pxcodes.com
然而,還有一些使用場(chǎng)景中你真的需要kill掉一個(gè)線程:比如,當(dāng)你封裝了一個(gè)外部庫(kù),但是這個(gè)外部庫(kù)在長(zhǎng)時(shí)間調(diào)用,因此你想中斷這個(gè)過(guò)程。r4P少兒編程網(wǎng)-https://www.pxcodes.com
【推薦:python視頻教程】r4P少兒編程網(wǎng)-https://www.pxcodes.com
解決方案 · 貳接下來(lái)的方案是允許在python線程里面raise一個(gè)Exception(當(dāng)然是有一些限制的)。r4P少兒編程網(wǎng)-https://www.pxcodes.com
def _async_raise(tid, exctype): '''Raises an exception in the threads with id tid''' if not inspect.isclass(exctype): raise TypeError("Only types can be raised (not instances)") res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype)) if res == 0: raise ValueError("invalid thread id") elif res != 1: # "if it returns a number greater than one, you're in trouble, # and you should call it again with exc=NULL to revert the effect" ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, 0) raise SystemError("PyThreadState_SetAsyncExc failed") class ThreadWithExc(threading.Thread): '''A thread class that supports raising exception in the thread from another thread. ''' def _get_my_tid(self): """determines this (self's) thread id CAREFUL : this function is executed in the context of the caller thread, to get the identity of the thread represented by this instance. """ if not self.isAlive(): raise threading.ThreadError("the thread is not active") # do we have it cached? if hasattr(self, "_thread_id"): return self._thread_id # no, look for it in the _active dict for tid, tobj in threading._active.items(): if tobj is self: self._thread_id = tid return tid # TODO: in python 2.6, there's a simpler way to do : self.ident raise AssertionError("could not determine the thread's id") def raiseExc(self, exctype): """Raises the given exception type in the context of this thread. If the thread is busy in a system call (time.sleep(), socket.accept(), ...), the exception is simply ignored. If you are sure that your exception should terminate the thread, one way to ensure that it works is: t = ThreadWithExc( ... ) ... t.raiseExc( SomeException ) while t.isAlive(): time.sleep( 0.1 ) t.raiseExc( SomeException ) If the exception is to be caught by the thread, you need a way to check that your thread has caught it. CAREFUL : this function is executed in the context of the caller thread, to raise an excpetion in the context of the thread represented by this instance. """ _async_raise( self._get_my_tid(), exctype )正如注釋里面描述,這不是啥“靈丹妙藥”,因?yàn)椋偃缇€程在python解釋器之外busy,這樣子的話終端異常就抓不到啦~r4P少兒編程網(wǎng)-https://www.pxcodes.com
這個(gè)代碼的合理使用方式是:讓線程抓住一個(gè)特定的異常然后執(zhí)行清理操作。這樣的話你就能終端一個(gè)任務(wù)并能合適地進(jìn)行清除。r4P少兒編程網(wǎng)-https://www.pxcodes.com
解決方案 · 叁假如我們要做個(gè)啥事情,類似于中斷的方式,那么我們就可以用thread.join方式。r4P少兒編程網(wǎng)-https://www.pxcodes.com
join的原理就是依次檢驗(yàn)線程池中的線程是否結(jié)束,沒(méi)有結(jié)束就阻塞直到線程結(jié)束,如果結(jié)束則跳轉(zhuǎn)執(zhí)行下一個(gè)線程的join函數(shù)。 先看看這個(gè): 1. 阻塞主進(jìn)程,專注于執(zhí)行多線程中的程序。 2. 多線程多join的情況下,依次執(zhí)行各線程的join方法,前頭一個(gè)結(jié)束了才能執(zhí)行后面一個(gè)。 3. 無(wú)參數(shù),則等待到該線程結(jié)束,才開(kāi)始執(zhí)行下一個(gè)線程的join。 4. 參數(shù)timeout為線程的阻塞時(shí)間,如 timeout=2 就是罩著這個(gè)線程2s 以后,就不管他了,繼續(xù)執(zhí)行下面的代碼。# coding: utf-8 # 多線程join import threading, time def doWaiting1(): print 'start waiting1: ' + time.strftime('%H:%M:%S') + " " time.sleep(3) print 'stop waiting1: ' + time.strftime('%H:%M:%S') + " " def doWaiting2(): print 'start waiting2: ' + time.strftime('%H:%M:%S') + " " time.sleep(8) print 'stop waiting2: ', time.strftime('%H:%M:%S') + " " tsk = [] thread1 = threading.Thread(target = doWaiting1) thread1.start() tsk.append(thread1) thread2 = threading.Thread(target = doWaiting2) thread2.start() tsk.append(thread2) print 'start join: ' + time.strftime('%H:%M:%S') + " " for tt in tsk: tt.join() print 'end join: ' + time.strftime('%H:%M:%S') + " "默認(rèn)join方式,也就是不帶參,阻塞模式,只有子線程運(yùn)行完才運(yùn)行其他的。r4P少兒編程網(wǎng)-https://www.pxcodes.com
1、 兩個(gè)線程在同一時(shí)間開(kāi)啟,join 函數(shù)執(zhí)行。r4P少兒編程網(wǎng)-https://www.pxcodes.com
2、waiting1 線程執(zhí)行(等待)了3s 以后,結(jié)束。r4P少兒編程網(wǎng)-https://www.pxcodes.com
3、waiting2 線程執(zhí)行(等待)了8s 以后,運(yùn)行結(jié)束。r4P少兒編程網(wǎng)-https://www.pxcodes.com
4、join 函數(shù)(返回到了主進(jìn)程)執(zhí)行結(jié)束。r4P少兒編程網(wǎng)-https://www.pxcodes.com
這里是默認(rèn)的join方式,是在線程已經(jīng)開(kāi)始跑了之后,然后再join的,注意這點(diǎn),join之后主線程就必須等子線程結(jié)束才會(huì)返回主線。r4P少兒編程網(wǎng)-https://www.pxcodes.com
join的參數(shù),也就是timeout參數(shù),改為2,即join(2),那么結(jié)果就是如下了:r4P少兒編程網(wǎng)-https://www.pxcodes.com
兩個(gè)線程在同一時(shí)間開(kāi)啟,join 函數(shù)執(zhí)行。r4P少兒編程網(wǎng)-https://www.pxcodes.com
wating1 線程在執(zhí)行(等待)了三秒以后,完成。r4P少兒編程網(wǎng)-https://www.pxcodes.com
join 退出(兩個(gè)2s,一共4s,36-32=4,無(wú)誤)。r4P少兒編程網(wǎng)-https://www.pxcodes.com
waiting2 線程由于沒(méi)有在 join 規(guī)定的等待時(shí)間內(nèi)(4s)完成,所以自己在后面執(zhí)行完成。r4P少兒編程網(wǎng)-https://www.pxcodes.com
join(2)就是:我給你子線程兩秒鐘,每個(gè)的2s鐘結(jié)束之后我就走,我不會(huì)有絲毫的顧慮!r4P少兒編程網(wǎng)-https://www.pxcodes.com
以上就是python如何終止線程的詳細(xì)內(nèi)容,更多請(qǐng)關(guān)注少兒編程網(wǎng)其它相關(guān)文章!r4P少兒編程網(wǎng)-https://www.pxcodes.com

- 上一篇
講解Python 基于文件操作實(shí)現(xiàn)購(gòu)物車
簡(jiǎn)介免費(fèi)學(xué)習(xí)推薦:python視頻教程Python基于文件操作實(shí)現(xiàn)購(gòu)物車學(xué)習(xí)Python有一段時(shí)間了,想著需要找些東西寫(xiě)一下來(lái)鞏固下基礎(chǔ),看到了購(gòu)物車然后想著能不能利用已經(jīng)學(xué)過(guò)的實(shí)現(xiàn)以下功能。但是比較簡(jiǎn)單的實(shí)現(xiàn)也沒(méi)啥意義,只用幾個(gè)循環(huán)和判斷寫(xiě)出來(lái)也沒(méi)用到些啥于是想著能不能更進(jìn)一步修改一下,做一個(gè)優(yōu)化。剛
- 下一篇
python怎么計(jì)算時(shí)間差
簡(jiǎn)介python計(jì)算時(shí)間差的方法:首先引入datetime包;然后通過(guò)“(time_2_struct-time_1_struct)”方式計(jì)算出同一天情形下的時(shí)間差或者不同天的時(shí)間差即可。本文操作環(huán)境:windows7系統(tǒng)、python2.7.14版,DELLG3電腦。python求時(shí)間差python求時(shí)