thread.start_new_thread 与 threading.Thread.start
python 中的 thread.start_new_thread
和 threading.Thread.start
有什么区别?
我注意到,当调用 start_new_thread
时,新线程会在调用线程终止后立即终止。 threading.Thread.start
则相反:调用线程等待其他线程终止。
What is the difference between thread.start_new_thread
and threading.Thread.start
in python?
I have noticed that when start_new_thread
is called, the new thread terminates as soon as the calling thread terminates. threading.Thread.start
is the opposite: the calling thread waits for other threads to terminate.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
thread
模块是 Python 的低级线程 API。不建议直接使用它,除非您确实需要。threading
模块是一个高级 API,构建在thread
之上。Thread.start
方法实际上是使用thread.start_new_thread
实现的。Thread
的daemon
属性必须在调用start
之前设置,指定线程是否应该是守护进程。当没有剩余活动的非守护线程时,整个 Python 程序将退出。默认情况下,daemon
为False
,因此该线程不是守护进程,因此该进程将等待其所有非守护线程退出,这是您的行为正在观察。PS
start_new_thread
确实是非常低级的。它只是 Python 核心线程启动器的一个薄包装,它本身调用操作系统线程生成函数。The
thread
module is the low-level threading API of Python. Its direct usage isn't recommended, unless you really need to. Thethreading
module is a high-level API, built on top ofthread
. TheThread.start
method is actually implemented usingthread.start_new_thread
.The
daemon
attribute ofThread
must be set before callingstart
, specifying whether the thread should be a daemon. The entire Python program exits when no alive non-daemon threads are left. By default,daemon
isFalse
, so the thread is not a daemon, and hence the process will wait for all its non-daemon thread to exit, which is the behavior you're observing.P.S.
start_new_thread
really is very low-level. It's just a thin wrapper around the Python core thread launcher, which itself calls the OS thread spawning function.请参阅 threading.Thread.daemon 标志 - 基本上只要没有非-守护线程正在运行,解释器终止。
See the threading.Thread.daemon flag - basically whenever no non-daemon threads are running, the interpreter terminates.