gpt4 book ai didi

python - Java Spring Boot 与 Python FastApi : Threads

转载 作者:行者123 更新时间:2023-12-05 08:45:23 27 4
gpt4 key购买 nike

我是 Java Spring Boot 开发人员,我开发 3 层 CRUD 应用程序。我和一个似乎对这个问题很了解的人交谈过,但我没有得到他的联系方式。他提倡 Python 的 FastApi,因为它的横向扩展比 Spring boot 更好。他提到的原因之一是 FastApi 是单线程的。当线程遇到数据库查找(或其他可以异步完成的工作)时,它会选择其他工作,以便稍后在数据库结果输入时返回到当前工作。在 Java 中,当有许多请求挂起时,线程游泳池可能会耗尽。

我 100% 不明白这个推理。让我扮演魔鬼的代言人。当 Python 程序遇到异步调用时,它必须以某种方式将程序指针存储在某个地方,以记住它需要在何处继续。我知道存储程序指针的那个地方根本不是线程,但我必须给它起个名字,所以我们称它为“逻辑线程”。在 Python 中,您可以有许多等待的逻辑线程。在 Java 中,您可以拥有一个包含许多正在等待的真实线程的线程池。对我来说,唯一的区别似乎是 Java 的线程是在操作系统级别管理的,而 Python 的“逻辑线程”是由 Python 或 FastApi 管理的。为什么在线程池中等待的真实线程比等待的逻辑线程要昂贵得多?如果我的大部分线程都在等待,为什么我不能增加线程池大小以避免耗尽?

最佳答案

问题中 Java 线程的问题由 Loom 项目解决,该项目计划包含在未来的 Jdk 中。这里解释得很好https://www.baeldung.com/openjdk-project-loom :

Presently, Java relies on OS implementations for both the continuation [of threads] and the scheduler [for threads].

Now, in order to suspend a continuation, it's required to store the entire call-stack. And similarly, retrieve the call-stack on resumption. Since the OS implementation of continuations includes the native call stack along with Java's call stack, it results in a heavy footprint.

A bigger problem, though, is the use of OS scheduler. Since the scheduler runs in kernel mode, there's no differentiation between threads. And it treats every CPU request in the same manner. (...)For example, consider an application thread which performs some action on the requests and then passes on the data to another thread for further processing. Here, it would be better to schedule both these threads on the same CPU. But since the [OS] scheduler is agnostic to the thread requesting the CPU, this is impossible to guarantee.

问题真正归结为 Why are OS threads considered expensive?

关于python - Java Spring Boot 与 Python FastApi : Threads,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73026698/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com