python3中Thread.setDeamon的使用

本文详细介绍了Python中守护线程的概念及使用方法。守护线程会在主线程结束时自动终止,确保程序正常退出。文章通过一个TCP多线程并发示例展示了如何设置守护线程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • setDaemon
语法:
	obj.setDaemon(True)
个人理解:
	* 需要在start之前使用
	* 主线程被创建时默认为False,所以子线程要设置时需要手动设置
	* Daemon意思为守护线程,用来回收线程,当主线程运行结束时,会被子线程杀死
  • 官方文档:
setDaemon()
   
   Old API for daemon.

 

    A boolean value indicating whether this thread is a daemon thread (True) or not (False). This must be set before start() is called, otherwise RuntimeError is raised. Its initial value is inherited from the creating thread; the main thread is not a daemon thread and therefore all threads created in the main thread default to daemon = False.

    The entire Python program exits when no alive non-daemon threads are left.

即是:
	setDaemon(True)将线程声明为守护线程,必须在start() 方法调用之前设置,如果不设置为守护线程程序会被无限挂起。当没有存活的非守护进程时,整个python程序才会退出。

总结:
	如果主线程执行完以后,还有其他非守护线程,主线程是不会退出的,会被无限挂起;必须将线程声明为守护线程之后,如果队列中的数据运行完了,那么整个程序想什么时候退出就退出,不用等待。
  • 代码实例:在tcp套接字多线程并发的示例
from socket import *
from  threading import *
import sys

#主线程接收请求
addr = ('0.0.0.0',8888)
sockfd = socket()
sockfd.bind(addr)
sockfd.listen(5)

while True:
	#创建子线程用来处理请求
	try:
		connfd,addr = sockfd.accept()
	except KeyboardInterrupt:
		#有异常则关闭套接字和父进程
		sockfd.close()
		sys.exit('服务器退出')
	
	#创建子线程并处理请求
	client_thread = Thread(target = handler,args = (connfd,))
	#设置子线程为守护线程,在主线程退出时自动退出
	client_thread.setDeamon(True)
	client_thread.start()

def handler(connfd):
	#线程处理函数
	pass

参考:https://bbs.youkuaiyun.com/topics/80298851

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值