解决Python父线程关闭后子线程不关闭问题
本文详解Python中父线程退出导致子线程滞留的问题。通过setDaemon(True)可让子线程随主线程自动结束,但需注意设置顺序。对于需要主动控制的场景,推荐继承Thread类并重写run方法,通过标志位实现线程的优雅终止,避免资源泄露。
父线程退出导致子线程滞留的原因
在Python中,利用threading模块可以方便地创建新线程。然而,当创建该线程的父线程意外终止时,对应的子线程可能并不会随之关闭。这种情况通常是因为在代码中未正确调用setDaemon(True)方法,导致子线程被视为非守护线程,从而在父线程结束后继续运行。
下面通过一个具体示例来演示这一现象及其解决方法。
import threading
def prt_hello() :
while 1 :
print 'hello'
if __name__ == '__main__' :
t = threading.Thread(target=prt_hello)
t.setDaemon(True)
t.start()
setDaemon的使用注意事项
需要注意的是,setDaemon方法的调用必须位于start方法之前,否则程序会抛出'cannot set daemon status of active thread'错误,导致设置失败。
补充知识:Python多线程退出/停止的一种实现思路
Python线程主动终止的实现思路
在使用多线程编程时,我们需要注意Python的线程对象并没有提供stop或terminate这样的直接方法。这意味着一旦线程被启动,除非整个主进程退出,否则无法主动强制终止它。这里强调的是主进程(Main Process)的退出,而非仅仅是父线程的结束。
自定义StoppableThread类示例
一种较为合理的做法是将原本需要在threading.Thread的target参数中指定的线程函数,改写为一个继承自Thread类的自定义类。通过这种方式,可以在类中封装线程的生命周期管理逻辑。以下是一个具体的实现示例。
import threading
import time
import os
# 原本需要用来启动的无线循环的函数
def print_thread():
pid = os.getpid()
counts = 0
while True:
print(f'threading pid: {pid} ran: {counts:04d} s')
counts += 1
time.sleep(1)
# 把函数放到改写到类的run方法中,便可以通过调用类方法,实现线程的终止
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父线程关闭后子线程不关闭问题的内容到此结束,希望能对读者有所帮助,也欢迎大家继续支持本站获取更多技术分享。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













