父线程退出时,Python守护程序线程不会退出

yer*_*989 8 python multithreading daemon

我有一些Python代码可以创建恶魔线程.父线程几乎立即结束,但守护程序线程保持打印睡眠.

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

内容sys.version:

'3.3.3 (v3.3.3:c3896275c0f6, Nov 18 2013, 21:19:30) [MSC v.1600 64 bit (AMD64)]'
Run Code Online (Sandbox Code Playgroud)

打印:

sleep

main thread end...

sleep

sleep

sleep
Run Code Online (Sandbox Code Playgroud)

当父线程退出时,为什么Python守护程序线程不会退出?

Eri*_*ski 7

如果thread.daemon = True为python线程指定,那么只剩下守护进程时程序将立即停止.发送到stdout的命令丢失了.

将其添加到名为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()
Run Code Online (Sandbox Code Playgroud)

像这样运行:

el@apollo:~/code/python/run01$ python --version
Python 2.7.6
el@apollo:~$ python main.py 
el@apollo:~$
Run Code Online (Sandbox Code Playgroud)

看到它打印没有,因为线程开始.您将其设置为守护程序并启动它.然后程序结束了.

额外注意事项:如果将此代码粘贴到python解释器中,则所有打印语句都将显示在终端上,因为守护程序永远不会失去与stdout的连接.

阅读更多:http://docs.python.org/2/library/threading.html

  • 此答案中提供的额外代码具有误导性,原始问题的真正答案是在 Python 解释器中运行会产生非退出行为,而作为脚本运行会产生预期行为。 (3认同)

dej*_*dej 5

如果从 python shell 完成,我只能重现 OP 描述的行为('sleep' 的无休止输出)。如果从文件运行,它会按预期工作(几行 'sleep' 和一行 'main thread end ...' )

同样,如果作为文件运行,第二个程序会立即退出,但在从 python shell 运行时也会打印无休止的“睡眠”语句。

我的结论:由于作为 python shell 的线程即使在“main”完成后继续运行,防止守护进程在从 python shell 运行时被终止。

这可以被认为是一个错误(即 Python 的行为取决于脚本的运行方式)还是预期的?我听从更有经验的 Pythonistas ......

顺便说一句 - 用 Python 3.2.3 测试