Do goroutines and light-weight Java threads mean we never need use thread pools and async code again?

huangapple go评论82阅读模式
英文:

Do goroutines and light-weight Java threads mean we never need use thread pools and async code again?

问题

我正在努力理解Goroutines(在Golang中)和轻量级线程(在Java 19+中)(以及其他语言中可能存在的情况)对编程意味着什么。

多年来,我们一直试图在各种语言中编写这种极难阅读、充斥着lambda函数的代码,基本上是设置了一系列回调函数,以在I/O完成或线程池开始处理时异步调用。这是因为线程创建一直是一项昂贵的操作,而且不能同时运行大量的操作系统线程。在我看来,这一直是一种非常丑陋的解决方法。

我还没有亲身体验过Goroutines或Java中的轻量级线程,但我觉得我们可以简单地回到编写直接的代码,因为这些类型的线程非常廉价。

这样说对吗?全力投入这些轻量级线程会有什么不利之处?

英文:

I'm trying to wrap my mind around what Goroutines (in Golang) and light-weight threads (in Java 19+) (and perhaps in other languages) mean for programming.

For years, we've been trying to write this extremely unreadable, lambda-function-heavy code in a variety of languages that basically sets up a chain of callbacks, to be invoked asynchronously once I/O is complete or a thread pool has gotten around to working on it. All because thread creation has been an expensive operation and one can't really run a gazillion of OS threads at the same time. In my view, this has always been a very ugly workaround.

I have no first-hand experience with either Goroutines or light-weight threads in Java yet, but it appears to me that we can simply go back to writing straightforward code because these kinds of threads are so cheap.

Is that correct? What would be the downsides of going all-in on those light-weight threads?

答案1

得分: 1

缺点是协作式多任务处理。这意味着在代码的虚拟线程逻辑中出现设计错误可能会导致固定一个真实线程并造成泄漏。而且,在这些线程中使用计算密集型逻辑并不是最佳方法。

换句话说,虚拟线程实际上并不是多线程代码,而是用于异步操作。然而,它们仍然使用熟悉的模式和方法,这些模式和方法对于真实线程是经典的。

英文:

The downside is cooperative multitasking. That means design mistakes in a virtual thread logic of code could lead to pinning a real thread and leaking them. And it is not the best approach to have computation intensive logic in such threads.

In other words, virtual threads are not multithreaded code in fact, but for asynchronous. However, they still use familiar patterns and approaches which are classical for real threads.

huangapple
  • 本文由 发表于 2023年1月15日 08:18:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/75122169.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定