Python守护程序线程和"与"声明

时间:2017-06-06 18:12:04

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

如果我在守护程序线程中有以下代码,并且主线程没有在守护程序上调用连接。该文件是否会安全关闭,因为它在"内使用"一旦主线程退出或没有?无论如何要保证安全吗?谢谢:D

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

1 个答案:

答案 0 :(得分:3)

来自docs

  

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

这表明,但并未完全声明,守护程序线程在没有__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()

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

的输出
in with block

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

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