thread.start_new_thread 与 threading.Thread.start

发布于 2024-11-05 04:13:44 字数 216 浏览 2 评论 0原文

python 中的 thread.start_new_threadthreading.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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

仙女山的月亮 2024-11-12 04:13:44

thread 模块是 Python 的低级线程 API。不建议直接使用它,除非您确实需要。 threading 模块是一个高级 API,构建在 thread 之上。 Thread.start方法实际上是使用thread.start_new_thread实现的。

Threaddaemon 属性必须在调用 start 之前设置,指定线程是否应该是守护进程。当没有剩余活动的非守护线程时,整个 Python 程序将退出。默认情况下,daemonFalse,因此该线程不是守护进程,因此该进程将等待其所有非守护线程退出,这是您的行为正在观察。


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. 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.

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 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.

久夏青 2024-11-12 04:13:44

请参阅 threading.Thread.daemon 标志 - 基本上只要没有非-守护线程正在运行,解释器终止。

See the threading.Thread.daemon flag - basically whenever no non-daemon threads are running, the interpreter terminates.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文