我正在学习有关线程之间共享数据,我偶然发现了这个不同的问题。据我了解,守护线程的主线程完成后杀害。简单的代码如下:
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窗口中运行。
有谁知道这里发生了什么?
谢谢 :)