我显然误解了有关 Python Thread 对象的守护进程属性的一些基本知识。
考虑以下:
daemonic.py
import sys, threading, time
class TestThread(threading.Thread):
def __init__(self, daemon):
threading.Thread.__init__(self)
self.daemon = daemon
def run(self):
x = 0
while 1:
if self.daemon:
print "Daemon :: %s" % x
else:
print "Non-Daemon :: %s" % x
x += 1
time.sleep(1)
if __name__ == "__main__":
print "__main__ start"
if sys.argv[1] == "daemonic":
thread = TestThread(True)
else:
thread = TestThread(False)
thread.start()
time.sleep(5)
print "__main__ stop"
来自 python 文档:
整个Python程序退出时
没有剩余任何活动的非守护线程。
因此,如果我使用 TestThread 作为守护进程运行,我希望它在主线程完成后退出。但这不会发生:
> python daemonic.py daemonic
__main__ start
Daemon :: 0
Daemon :: 1
Daemon :: 2
Daemon :: 3
Daemon :: 4
__main__ stop
Daemon :: 5
Daemon :: 6
^C
我没有得到什么?
正如 Justin 和 Brent 所猜测的,我正在使用 Python 2.5 运行。刚回到家并在我自己的运行 2.7 的机器上进行了尝试,一切正常。感谢您的帮助!
您对守护线程的理解should做是正确的。
至于为什么没有发生这种情况,我猜你正在使用旧版本的Python。 Python 2.5.4 文档包括setDaemon(daemonic)
函数,以及isDaemon()
检查线程是否是守护线程。 2.6 文档将这些替换为可直接修改的daemon
flag.
参考:
http://docs.python.org/release/2.5.4/ http://docs.python.org/release/2.5.4/ (no daemon
提到的成员)
http://docs.python.org/release/2.6/library/threading.html http://docs.python.org/release/2.6/library/threading.html(包括daemon
member)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)