为什么这些守护线程没有被杀死?

Why don't these daemon threads get killed?

我在学习如何在线程之间共享数据时偶然发现了这个不同的问题。据我了解,守护线程在主线程完成后被杀死。简单代码如下:

import threading
from time import sleep

def thread(Nr):
    global x
    lock.acquire()
    x = Nr
    print(x)
    sleep(4)
    print(x)
    lock.release()

    return 0

#################################################################################

x = 2
lock = threading.Lock()

for i in range(6):
    #print("Thread Nr: ", i)
    arg1 = i
    t = threading.Thread(target = thread, args = (arg1,), name = arg1)
    t.setDaemon(True)
    print("new thread started : %s" % (str(threading.current_thread().ident)))    
    t.start()
    sleep(1)

print("Main thread end")

我正在启动 6 个线程,这是我在 IDLE python 3.7.2:

中的输出
new thread started : 940
0
new thread started : 940
new thread started : 940
new thread started : 940
new thread started : 9400

1
new thread started : 940
Main thread end
>>> 1
2
2
3
3
4
4
5
5

因此,如您所见,线程在主线程之后继续 运行,即使它们是守护线程。我发现的一件有趣的事情是 如果它们是来自 windows cmd 而不是 IDLE 的 运行,那么它们不会在 "Main thread end" 之后打印任何内容。

有人知道这里发生了什么吗?

谢谢:)

他们这样做,但不是在您的 IDLE 中。

运行 IDLE 中的东西不是你应该依赖的东西。重要的是你的命令提示符。例如,您不能真正在 IDLE 中使用 Multiprocessing 库。

就您的 IDLE 而言,我相信线程会继续,因为在 shell(IDLE) 中,您实际上并没有完成您的 script/program。您可以添加新命令的事实表明,您的程序仍在 运行 - 等待您下一次输入的形式。

Shell 就像脚本末尾带有(见下文)的程序

while True:
    exec(raw_input('>>> '))

这意味着,您的主线程仍然是 运行,因此无论您将守护进程设置为 true 还是 false 都没有关系

如果您想亲眼看看,请在打印后添加

exit(0)

看看会发生什么