Python 守护线程和 "with"语句

标签 python python-2.7 daemon python-multithreading with-statement

如果我在守护线程中有以下代码并且主线程不调用守护进程上的连接。一旦主线程退出或不退出,文件是否会安全关闭,因为它在“with”内部使用?无论如何让它安全?谢谢 :D

while True:
    with open('file.txt', 'r') as f:
        cfg = f.readlines()
time.sleep(60)

最佳答案

来自docs :

Note: Daemon threads are abruptly stopped at shutdown. Their resources (such as open files, database transactions, etc.) may not be released properly. If you want your threads to stop gracefully, make them non-daemonic and use a suitable signalling mechanism such as an Event.

这表明,但并没有完全声明,守护线程在 __exit__ 方法和 finally block 没有机会运行的情况下被终止。我们可以运行一个实验来验证情况是否如此:

import contextlib
import threading
import time

@contextlib.contextmanager
def cm():
    try:
        yield
    finally:
        print 'in __exit__'

def f():
    with cm():
        print 'in with block'
        event.set()
        time.sleep(10)

event = threading.Event()

t = threading.Thread(target=f)
t.daemon = True
t.start()

event.wait()

我们启动一个守护线程并在主线程退出时让它在 with block 中休眠。当我们run the experiment ,我们得到输出

in with block

但是 __exit__ 中没有,所以 __exit__ 方法永远没有机会运行。


如果你想要清理,不要使用守护线程。使用常规线程,并通过常规线程间通信 channel 告诉它在主线程结束时关闭。

关于Python 守护线程和 "with"语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44397009/

相关文章:

python - 为什么我不能在 wxPython 中销毁我的 StaticText?

python - 对 Python 中 time.clock 的行为感到困惑

java - 如果我们可以使用普通线程,为什么还要使用守护线程。守护线程可以做但普通线程不能做的事情是什么

python - Pathlib 使用 Path.parents 访问 Path 时出错

java - 从databricks连接到数据库时获取java.lang.ClassNotFoundException : com. mysql.jdbc.Driver

python - 根据python中训练和测试集的时间戳为每个用户拆分数据集

python - Systemd 服务不执行我的 Python 脚本

python - mod_wsgi.so 适用于 windows 7 64 位?

python - 解析两个相似的html文件的时间差异很大

shell - 无法连接到 CentOS 6.10 上的 Daemon Deluge