Python守护程序线程和“ with”语句

Sam*_*mas 4 python daemon with-statement python-multithreading python-2.7

如果我在守护程序线程中有以下代码,而主线程没有在守护程序上调用联接。一旦主线程退出或不退出,文件是否会在“ with”内部使用而安全关闭?无论如何要使其安全?感谢:D

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

use*_*ica 5

文档

注意:守护程序线程在关闭时突然停止。它们的资源(例如打开的文件,数据库事务等)可能无法正确释放。如果希望线程正常停止,请使其成为非守护进程,并使用适当的信号机制,例如事件。

这表明(但不是完全声明)守护程序线程被终止而没有机会运行__exit__方法和finally块。我们可以运行一个实验来验证是否是这种情况:

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()
Run Code Online (Sandbox Code Playgroud)

在其中启动守护程序线程,并with在主线程退出时将其休眠在一个块中。当我们运行实验时,我们得到的输出

in with block
Run Code Online (Sandbox Code Playgroud)

但没有in __exit__,因此该__exit__方法永远不会有运行的机会。


如果要清理,请不要使用守护线程。使用常规线程,并通过常规线程间通信通道告诉它在主线程末端关闭。