解決python父線程關(guān)閉后子線程不關(guān)閉問題
我們都知道,python可以通過threading module來創(chuàng)建新的線程,然而在創(chuàng)建線程的線程(父線程)關(guān)閉之后,相應(yīng)的子線程可能卻沒有關(guān)閉,這可能是因為代碼中沒有使用setDaemon(True)函數(shù)。
接下來,使用一個例子來說明:
import threading def prt_hello() : while 1 : print 'hello' if __name__ == '__main__' : t = threading.Thread(target=prt_hello) t.setDaemon(True) t.start()
我們需要把setDaemon函數(shù)放在start函數(shù)前面,不然它是不給通過的,并且返回'cannot set daemon status of active thread‘
補(bǔ)充知識:Python 多線程的退出/停止的一種是實現(xiàn)思路
在使用多線程的過程中,我們知道,python的線程是沒有stop/terminate方法的,也就是說它被啟動后,你無法再主動去退出它,除非主進(jìn)程退出了,注意,是主進(jìn)程,不是線程的父進(jìn)程.
一個比較合理的方式就是把原因需要放到threading.Thread的target中的線程函數(shù),改寫到一個繼承類中,下面是一個實現(xiàn)例子
import threading import time import os # 原本需要用來啟動的無線循環(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ù)放到改寫到類的run方法中,便可以通過調(diào)用類方法,實現(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) # 主動把線程退出 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)閉問題就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Selenium向iframe富文本框輸入內(nèi)容過程圖解
這篇文章主要介紹了Selenium向iframe富文本框輸入內(nèi)容過程圖解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-04-04一文帶你掌握Python?Seaborn數(shù)據(jù)可視化高級篇
這篇文章主要為大家詳細(xì)介紹了如何使用?Seaborn?創(chuàng)建復(fù)合圖形,如網(wǎng)格圖、因子圖和聚類熱圖等,文中示例代碼講解詳細(xì),感興趣的小伙伴可以學(xué)習(xí)一下2023-07-07python中的class_static的@classmethod的巧妙用法
python中的class_static的@classmethod的使用 classmethod的使用,主要針對的是類而不是對象,在定義類的時候往往會定義一些靜態(tài)的私有屬性,今天通過示例代碼看下classmethod的妙用2021-06-06Pandas數(shù)據(jù)分析之groupby函數(shù)用法實例詳解
這篇文章主要為大家介紹了Pandas數(shù)據(jù)分析之groupby函數(shù)用法實例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-10-10python腳本監(jiān)控Tomcat服務(wù)器的方法
這篇文章主要介紹了利用python腳本監(jiān)控Tomcat服務(wù)器的方法,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2018-07-07python星號(*)和雙星號(**)?函數(shù)動態(tài)參數(shù)匹配及解包操作方法
這篇文章主要介紹了python星號(*)和雙星號(**)?函數(shù)動態(tài)參數(shù)匹配及解包操作,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-03-03