久久福利_99r_国产日韩在线视频_直接看av的网站_中文欧美日韩_久久一

您的位置:首頁技術文章
文章詳情頁

解決python父線程關閉后子線程不關閉問題

瀏覽:26日期:2022-07-27 15:02:27

我們都知道,python可以通過threading module來創(chuàng)建新的線程,然而在創(chuàng)建線程的線程(父線程)關閉之后,相應的子線程可能卻沒有關閉,這可能是因為代碼中沒有使用setDaemon(True)函數(shù)。

接下來,使用一個例子來說明:

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ù)前面,不然它是不給通過的,并且返回’cannot set daemon status of active thread‘

補充知識:Python 多線程的退出/停止的一種是實現(xiàn)思路

在使用多線程的過程中,我們知道,python的線程是沒有stop/terminate方法的,也就是說它被啟動后,你無法再主動去退出它,除非主進程退出了,注意,是主進程,不是線程的父進程.

一個比較合理的方式就是把原因需要放到threading.Thread的target中的線程函數(shù),改寫到一個繼承類中,下面是一個實現(xiàn)例子

import threadingimport timeimport 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父線程關閉后子線程不關閉問題就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。

標簽: Python 編程
相關文章:
主站蜘蛛池模板: 在线不卡视频 | 国产一级大片 | 国产三级电影 | 日韩不卡一区二区三区 | 欧美午夜一区 | 不卡一二区 | 日韩爱爱视频 | 在线观看免费毛片视频 | 中文字幕一区二区三区四区不卡 | 999免费视频| 欧美精产国品一二三区 | 日韩国产在线观看 | 射久久| 国产在线精品一区二区 | 99re6在线视频精品免费 | 中国一级毛片 | 欧美日韩一区二区三区在线电影 | 日韩91| 成人黄色a| 91精品久久久久久久久中文字幕 | 91在线综合 | 久久黑人| 国产精品久久久久久久岛一牛影视 | 国产精品久久久久久吹潮 | 亚洲欧洲视频在线 | 黑人巨大精品欧美一区免费视频 | 国产一级免费 | 一本一道久久a久久精品综合蜜臀 | 久久毛片 | 久久亚洲二区 | 欧美日韩国产在线观看 | 欧美日韩久久久 | 狠狠爱天天干 | 少妇精品视频在线观看 | 色综合久久天天综合网 | 最新国产精品 | 日日爱夜夜操 | 亚洲国产成人av好男人在线观看 | 男人超碰| 亚洲精品视频在线 | 色精品视频 |