为什么不把这些守护线程被杀?

问题描述 投票:0回答:1

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

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个线程,这是我在空闲的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

所以,你可以看到线程继续即使他们deamonic主线程之后运行。我发现一个有趣的事情是,他们不“主线程结束”后打印任何东西,如果他们是从在cmd而不是IDLE窗口中运行。

有谁知道这里发生了什么?

谢谢 :)

python multithreading daemon hang
1个回答
0
投票

他们这样做,但不是在你的空闲。

在怠速运转的东西是不是你应该依靠。重要的是你的命令提示符。例如,你不能真正使用多重库与你的空闲。

至于你的空闲而言,我相信线程continiue,因为在外壳(IDLE),你不真正完成你的脚本/程序。在等待你的下一个输入形式 - 张女士,您可以添加新的命令,表演,你的程序仍在运行。

壳牌是喜欢用程序(见下文)在脚本结束

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

这意味着,你的主线程仍然在运行,所以你是否设置守护进程真或假并不重要

如果你想看到自己,增加打印后

exit(0)

看看会发生什么

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.