python 会在退出之前等待所有线程完成吗?

Will python wait for all threads to finish before exiting?

我有以下 python 脚本:

script.py

from threading import Thread

def func():
    while True:
        pass

a = Thread(target=func)
a.start()

print('started the thread')

当从终端 (python script.py) 运行 时,它打印 started the thread 并挂在那里。来自 C 背景,我知道主线程何时完成,其余线程也将终止。 Python 不是这样吗?即使没有调用 a.join(),python 也会等待吗? python有主线程的概念还是所有线程都一样?

Python中有一个“主线程”,一般是启动Python解释器的线程。 threading 模块创建的线程在本机 OS 线程之上有一些行为层。其中一种行为是,当解释器退出时,正常关闭处理的一部分是主线程加入每个 non-daemon threading.Thread - 所以,是的,Python 通常等待所有其他线程结束。

当 Python 退出时守护进程 threading.Thread 是否被强制关闭取决于 OS,尽管我相信所有主要操作系统现在都会杀死它们。

如果不管non-daemon threading.Thread是否是运行都想退出解释器,需要kill这个job,或者调用os._exit()。注意前导下划线!不推荐,但如果你需要它就在那里。