thread.start_new_thread与threading.Thread.start [英] thread.start_new_thread vs 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.
推荐答案
thread
模块是Python的低级线程API.不建议直接使用它,除非您确实需要. threading
模块是建立在thread
之上的高级API. Thread.start
方法实际上是使用thread.start_new_thread
实现的.
The thread
module is the low-level threading API of Python. Its direct usage isn't recommended, unless you really need to. The threading
module is a high-level API, built on top of thread
. The Thread.start
method is actually implemented using thread.start_new_thread
.
必须在调用start
之前设置Thread
的daemon
属性,指定线程是否应该是守护程序.当没有活动的非守护线程时,整个Python程序将退出.默认情况下,daemon
是False
,因此该线程不是守护程序,因此该进程将等待其所有非守护程序线程退出,这是您正在观察的行为.
The daemon
attribute of Thread
must be set before calling start
, specifying whether the thread should be a daemon. The entire Python program exits when no alive non-daemon threads are left. By default, daemon
is False
, 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
确实是非常低级的.它只是Python核心线程启动器的一个薄包装,它本身称为OS线程生成功能.
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.
这篇关于thread.start_new_thread与threading.Thread.start的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!