问题描述
我有一些创建恶魔线程的Python代码.父线程几乎立即结束,但守护程序线程保持打印睡眠状态.
I have some Python code that creates a demon thread. The parent thread ends almost immediately, but the daemon thread keeps printing sleep.
import threading
import time
def int_sleep():
for _ in range(1, 600):
time.sleep(1)
print("sleep")
def main():
thread = threading.Thread(target=int_sleep)
thread.daemon = True
thread.start()
time.sleep(2)
print("main thread end...")
thread = threading.Thread(target=main)
thread.start()
sys.version:
sys.version:
'3.3.3 (v3.3.3:c3896275c0f6, Nov 18 2013, 21:19:30) [MSC v.1600 64 bit (AMD64)]'
打印:
sleep
main thread end...
sleep
sleep
sleep
为什么父线程退出时Python守护进程线程不退出?
Why doesn't the Python daemon thread exit when parent thread exits?
推荐答案
如果为python线程指定thread.daemon = True
,则仅保留守护程序时,程序将立即停止.发送到标准输出的命令将丢失.
If you specify thread.daemon = True
for your python thread, then the program will halt immediately when only the daemon is left. The the commands sent to stdout are lost.
将此添加到名为main.py的文件中
Add this to a file called main.py
import threading
import time
def int_sleep():
for _ in range(1, 600):
time.sleep(1)
print("sleep")
def main():
thread = threading.Thread(target=int_sleep)
thread.daemon = True
thread.start()
time.sleep(2)
print("main thread end...")
thread = threading.Thread(target=main)
thread.daemon = True
thread.start()
像这样运行它:
el@apollo:~/code/python/run01$ python --version
Python 2.7.6
el@apollo:~$ python main.py
el@apollo:~$
看到它不打印任何内容,因为线程已启动.您将其设置为守护程序并启动它.然后程序结束.
See it prints nothing because the thread started. You set it to be a daemon and started it. Then the program ended.
附加说明:如果将此代码粘贴到python解释器中,则所有打印语句将出现在终端上,因为守护程序永远不会失去与stdout的连接.
Extra notes: If you paste this code into a python interpreter, all the print statements will appear on the terminal because the daemon never loses hold of its connection to stdout.
了解更多: http://docs.python.org/2/library/threading .html
这篇关于当父线程退出时,Python守护进程线程不会退出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!