解決python父線程關(guān)閉后子線程不關(guān)閉問(wèn)題
我們都知道,python可以通過(guò)threading module來(lái)創(chuàng)建新的線程,然而在創(chuàng)建線程的線程(父線程)關(guān)閉之后,相應(yīng)的子線程可能卻沒(méi)有關(guān)閉,這可能是因?yàn)榇a中沒(méi)有使用setDaemon(True)函數(shù)。
接下來(lái),使用一個(gè)例子來(lái)說(shuō)明:
import threadingdef prt_hello() : while 1 : print ’hello’if __name__ == ’__main__’ : t = threading.Thread(target=prt_hello) t.setDaemon(True) t.start()
我們需要把setDaemon函數(shù)放在start函數(shù)前面,不然它是不給通過(guò)的,并且返回’cannot set daemon status of active thread‘
補(bǔ)充知識(shí):Python 多線程的退出/停止的一種是實(shí)現(xiàn)思路
在使用多線程的過(guò)程中,我們知道,python的線程是沒(méi)有stop/terminate方法的,也就是說(shuō)它被啟動(dòng)后,你無(wú)法再主動(dòng)去退出它,除非主進(jìn)程退出了,注意,是主進(jìn)程,不是線程的父進(jìn)程.
一個(gè)比較合理的方式就是把原因需要放到threading.Thread的target中的線程函數(shù),改寫(xiě)到一個(gè)繼承類(lèi)中,下面是一個(gè)實(shí)現(xiàn)例子
import threadingimport timeimport os # 原本需要用來(lái)啟動(dòng)的無(wú)線循環(huán)的函數(shù)def print_thread(): pid = os.getpid() counts = 0 while True: print(f’threading pid: {pid} ran: {counts:04d} s’) counts += 1 time.sleep(1) # 把函數(shù)放到改寫(xiě)到類(lèi)的run方法中,便可以通過(guò)調(diào)用類(lèi)方法,實(shí)現(xiàn)線程的終止class StoppableThread(threading.Thread): def __init__(self, daemon=None): super(StoppableThread, self).__init__(daemon=daemon) self.__is_running = True self.daemon = daemon def terminate(self): self.__is_running = False def run(self): pid = os.getpid() counts = 0 while self.__is_running: print(f’threading running: {pid} ran: {counts:04d} s’) counts += 1 time.sleep(1) def call_thread(): thread = StoppableThread() thread.daemon = True thread.start() pid = os.getpid() counts = 0 for i in range(5): print(f’0 call threading pid: {pid} ran: {counts:04d} s’) counts += 2 time.sleep(2) # 主動(dòng)把線程退出 thread.terminate() if __name__ == ’__main__’: call_thread() print(f’==========call_thread finish===========’) counts = 0 for i in range(5): counts += 1 time.sleep(1) print(f’main thread:{counts:04d} s’)
以上這篇解決python父線程關(guān)閉后子線程不關(guān)閉問(wèn)題就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. ajax請(qǐng)求后臺(tái)得到j(luò)son數(shù)據(jù)后動(dòng)態(tài)生成樹(shù)形下拉框的方法2. phpstudy apache開(kāi)啟ssi使用詳解3. JSP之表單提交get和post的區(qū)別詳解及實(shí)例4. Xml簡(jiǎn)介_(kāi)動(dòng)力節(jié)點(diǎn)Java學(xué)院整理5. 詳解瀏覽器的緩存機(jī)制6. .Net Core和RabbitMQ限制循環(huán)消費(fèi)的方法7. jsp實(shí)現(xiàn)登錄驗(yàn)證的過(guò)濾器8. jsp文件下載功能實(shí)現(xiàn)代碼9. ASP動(dòng)態(tài)網(wǎng)頁(yè)制作技術(shù)經(jīng)驗(yàn)分享10. 存儲(chǔ)于xml中需要的HTML轉(zhuǎn)義代碼
