【发布时间】:2019-02-06 20:24:51
【问题描述】:
我在学习如何在线程之间共享数据时偶然发现了这个不同的问题。据我了解,守护线程在主线程完成后被杀死。简单代码如下:
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 运行,它们在“主线程结束”之后不会打印任何内容。
有人知道这里发生了什么吗?
谢谢:)
【问题讨论】:
-
如果您的问题已得到解答,请确保接受答案以供进一步参考。
标签: python multithreading daemon freeze