Python 守护线程和 "with" 语句
Python daemon threads and the "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
块到 运行 的情况下被终止。我们可以运行一个实验来验证是这样的:
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__
方法永远没有机会 运行.
如果要清理,请不要使用守护线程。使用常规线程,并通过常规线程间通信通道告诉它在主线程结束时关闭。
如果我在守护线程中有以下代码并且主线程不调用守护进程上的连接。一旦主线程退出或不退出,文件是否会安全关闭,因为它在 "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
块到 运行 的情况下被终止。我们可以运行一个实验来验证是这样的:
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__
方法永远没有机会 运行.
如果要清理,请不要使用守护线程。使用常规线程,并通过常规线程间通信通道告诉它在主线程结束时关闭。