Python 的 daemon 线程的精讲---通透

关于 Python 中的 daemon 的设置说明:
https://www.cnblogs.com/xfiver/p/5189732.html

Daemons are only useful when the main program is running,
and it’s okay to kill them off once the other non-daemon threads have exited.
Without daemon threads, we have to keep track of them, and tell them to exit, before our program can completely quit.
By setting them as daemon threads,
we can let them run and forget about them, and when our program quits, any daemon threads are killed automatically.
Daemon线程当且仅当主线程运行时有效,当其他非Daemon线程结束时可自动杀死所有Daemon线程。
如果没有Daemon线程的定义,则必须手动的跟踪这些线程,在程序结束前手动结束这些线程。
通过设置线程为Daemon线程,则可以放任它们运行,并遗忘它们,当主程序结束时这些Daemon线程将自动被杀死。

Python主程序当且仅当不存在 非Daemon 线程存活时退出。
即:主程序等待所有非Daemon线程结束后才退出,且退出时会自动结束(很粗鲁的结束)所有Daemon线程。

亦理解为:Daemon设置为子线程是否随主线程一起结束,默认为False。如果要随主线程一起结束需要设置为True。

import time, threading
import datetime
def run_thread(n , b):
    print '{0}: In run_thread: Current thead is {1}'.format(datetime.datetime.now(), threading.current_thread())
    print '{0}: n = {1}'.format(datetime.datetime.now(), n)
    time.sleep(5)
    print '{0}: b = {1}'.format(datetime.datetime.now(), b)
print '{0}: Current thead is {1}'.format(datetime.datetime.now(),threading.current_thread())

# Case1: 在主进程中调用 t1.join() 时,主进程会阻塞在该处并且等待子线程结束
# root@robert-Ubuntu:/media/sf_WorkSpace/HelloNG/src/testcode# python threading_daemon.py
# 2020-06-30 11:16:07.808415: Current thead is <_MainThread(MainThread, started 140504184133376)>
# 2020-06-30 11:16:07.808678: t1.daemon = False
# 2020-06-30 11:16:07.809016: In run_thread: Current thead is <Thread(first thread with customized name, started 140504165930752)>
# 2020-06-30 11:16:07.809145: n = 5
# 2020-06-30 11:16:12.814438: b = 3
# 2020-06-30 11:16:12.814633: end of the process!!!
# root@robert-Ubuntu:/media/sf_WorkSpace/HelloNG/src/testcode#
# t1 = threading.Thread(target=run_thread, args=(5,3), name = 'first thread with customized name')
# print '{0}: t1.daemon = {1}'.format(datetime.datetime.now(), t1.daemon)
# t1.start()
# t1.join()
# print '{0}: end of the process!!!'.format(datetime.datetime.now())
#
# Case2: 当主进程 没有调用 t1.join() 且运行到结束的时候: 如果子线程的 daemon 值为 False,则依然会等待子线程结束
# Python主程序当且仅当不存在 非Daemon 线程存活时退出。
# 即:主程序等待所有非Daemon线程结束后才退出,且退出时会自动结束(很粗鲁的结束)所有Daemon线程。
# 亦理解为:Daemon设置为子线程是否随主线程一起结束,默认为False。如果要随主线程一起结束需要设置为True。
# from: https://www.cnblogs.com/xfiver/p/5189732.html
# root@robert-Ubuntu:/media/sf_WorkSpace/HelloNG/src/testcode# python threading_daemon.py
# 2020-06-30 11:16:54.185968: Current thead is <_MainThread(MainThread, started 139965824337664)>
# 2020-06-30 11:16:54.186078: t1.daemon = False
# 2020-06-30 11:16:54.186558: In run_thread: Current thead is <Thread(first thread with customized name, started 139965806135040)>
#  2020-06-30 11:16:54.186912: n = 5
# 2020-06-30 11:16:54.186664: end of the process!!!
# 2020-06-30 11:16:59.194845: b = 3
# root@robert-Ubuntu:/media/sf_WorkSpace/HelloNG/src/testcode#
#
t1 = threading.Thread(target=run_thread, args=(5,3), name = 'first thread with customized name')
print '{0}: t1.daemon = {1}'.format(datetime.datetime.now(), t1.daemon)
t1.start()
print '{0}: end of the process!!!'.format(datetime.datetime.now())

# Case 3: 当主进程 没有调用 t1.join() 且运行到结束的时候: 如果子线程的 daemon 值为 True,则主进程在自己退出的时候会粗暴的结束子线程
#         可以通过 ps -eLf | grep process_name 来验证“主进程在自己退出的时候会粗暴的结束子线程”而不是放任不管它
# root@robert-Ubuntu:/media/sf_WorkSpace/HelloNG/src/testcode# python threading_daemon.py
# 2020-06-30 11:18:05.438126: Current thead is <_MainThread(MainThread, started 139762719913728)>
# 2020-06-30 11:18:05.438258: t1.daemon = True
# 2020-06-30 11:18:05.438677: In run_thread: Current thead is <Thread(first thread with customized name, started daemon 139762701711104)>
#  2020-06-30 11:18:05.439043: n = 5
# 2020-06-30 11:18:05.438808: end of the process!!!
# root@robert-Ubuntu:/media/sf_WorkSpace/HelloNG/src/testcode#
#
# t1 = threading.Thread(target=run_thread, args=(5,3), name = 'first thread with customized name')
# t1.setDaemon(True)
# print '{0}: t1.daemon = {1}'.format(datetime.datetime.now(), t1.daemon)
# t1.start()
# print '{0}: end of the process!!!'.format(datetime.datetime.now())
`python-daemon` 是一个Python库,用于将你的应用程序转换为守护进程(daemon)。它提供了一种简单的方法,可以让你的应用程序在后台运行,并且具有守护进程的特性,如自动重启、日志记录等。 下面是使用 `python-daemon` 库的基本步骤: 1. 安装 `python-daemon` 库:使用 `pip` 命令安装 `python-daemon` 库: ```bash pip install python-daemon ``` 2. 导入必要的模块:在你的Python代码中,导入 `daemon` 模块和其他需要使用的模块。 ```python import daemon import time ``` 3. 编写你的应用程序逻辑:在你的代码中编写应用程序的逻辑。这可以是一个函数或一个类。 ```python def my_application_logic(): while True: # 在这里编写你的应用程序逻辑 print("Running...") time.sleep(1) ``` 4. 使用 `daemon.DaemonContext` 转换为守护进程:在主程序中使用 `daemon.DaemonContext` 上下文管理器将你的应用程序转换为守护进程。 ```python with daemon.DaemonContext(): my_application_logic() ``` 这将使你的应用程序在后台以守护进程的形式运行。当你运行这段代码时,它将在后台持续运行,并且你的终端会立即返回。 5. 运行你的代码:运行你的Python脚本,将其转换为守护进程。 ```bash python your_script.py ``` 现在,你的应用程序将在后台作为守护进程运行,并且你可以通过日志文件或其他机制来记录输出和错误。 请注意,守护进程转换后,不会再有终端输出。你可以使用日志记录或其他方法来捕获和处理输出。同时,确保在你的应用程序中正确处理异常,并在必要时进行重启等操作。 这只是一个简单的示例,你可以根据自己的需求和应用程序的逻辑进行更复杂的设置和优化。详细了解 `python-daemon` 库的文档可以帮助你更好地使用和配置守护进程。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值