色综合图-色综合图片-色综合图片二区150p-色综合图区-玖玖国产精品视频-玖玖香蕉视频

您的位置:首頁技術(shù)文章
文章詳情頁

解決python父線程關(guān)閉后子線程不關(guān)閉問題

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

我們都知道,python可以通過threading module來創(chuàng)建新的線程,然而在創(chuàng)建線程的線程(父線程)關(guān)閉之后,相應(yīng)的子線程可能卻沒有關(guān)閉,這可能是因為代碼中沒有使用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父線程關(guān)閉后子線程不關(guān)閉問題就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。

標簽: Python 編程
相關(guān)文章:
主站蜘蛛池模板: 在线观看91精品国产入口 | 久久久久久久久久久久久久久久久久 | 日韩欧美国产另类 | 97操碰 | 夜间福利在线观看 | 目韩一区二区三区系列片丶 | 色樱桃影院亚洲精品影院 | 日韩三级欧美 | 精品久久久久久久久中文字幕 | 国产欧美日韩综合精品无毒 | 亚洲欧美精品中文字幕 | 亚洲精品播放 | 毛片在线高清免费观看 | 国产一区私人高清影院 | 美女在线网站免费的 | 欧美 亚洲 丝袜 清纯 中文 | 黄色18网站| 一级v片| 久久99精品久久久久久久不卡 | 99re热精品这里精品 | 国产精品永久免费视频观看 | 国产在线精品一区二区不卡 | 免费三级毛片 | 性刺激免费视频观看在线观看 | 波多野结衣一级 | 日韩一级欧美一级 | 日日摸人人看97人人澡 | 99精品国产成人一区二区在线 | 久久精品国产影库免费看 | 日本韩国一级片 | 日本午夜视频 | 男人使劲躁女人视频小v | 国产成人毛片精品不卡在线 | 亚洲国产精品一区二区久 | 日本护士一级毛片在线播放 | 国产精品一区二区手机在线观看 | 成人午夜大片免费看爽爽爽 | 香蕉超级碰碰碰97视频在线观看 | 国产成人一区二区三区 | 欧美啪啪一级毛片 | 久爱免费观看在线网站 |