英文:
Why are goroutines much cheaper than threads in other languages?
问题
在他的演讲中(https://blog.golang.org/concurrency-is-not-parallelism),Rob Pike说go协程类似于线程,但要便宜得多。有人可以解释一下为什么吗?
英文:
In his talk - https://blog.golang.org/concurrency-is-not-parallelism, Rob Pike says that go routines are similar to threads but much much cheaper. Can someone explain why?
答案1
得分: 5
请参阅“Goroutine的工作原理”。它们在以下方面更加节省资源:
- 内存消耗:
与几KB的线程相比,线程启动时需要大量内存。 - 设置和拆除成本:
(这就是为什么你需要维护一个线程池) - 切换成本:
线程是抢占式调度的,而在线程切换期间,调度器需要保存/恢复所有寄存器。
与Go不同,Go运行时从创建到调度再到拆除都管理着goroutine。而且需要保存的寄存器数量较少。
此外,正如“Go的低延迟GC之路”中提到的,当运行时负责管理goroutine时,实现GC更容易:
> 自从Go 1.5引入并发GC以来,运行时一直跟踪goroutine自上次扫描其堆栈以来是否已执行。标记终止阶段将检查每个goroutine,以查看它们是否最近运行,并重新扫描其中的一些。
>
> 在Go 1.7中,运行时维护了一个单独的短列表来存储这些goroutine。这样就不需要在用户代码暂停时遍历整个goroutine列表,并且大大减少了可能触发内核NUMA相关内存迁移代码的内存访问次数。
英文:
See "How goroutines work".
They are cheaper in:
- memory consumption:
A thread starts with a large memory as opposed to a few Kb. - Setup and teardown costs
(That is why you have to maintain a pool of thread) - Switching costs
Threads are scheduled preemptively, and during a thread switch, the scheduler needs to save/restore ALL registers.
As opposed to Go where the the runtime manages the goroutines throughout from creation to scheduling to teardown. And the number of registers to save is lower.
Plus, as mentioned in "Go’s march to low-latency GC", a GC is easier to implement when the runtime is in charge of managing goroutines:
> Since the introduction of its concurrent GC in Go 1.5, the runtime has kept track of whether a goroutine has executed since its stack was last scanned. The mark termination phase would check each goroutine to see whether it had recently run, and would rescan the few that had.
>
> In Go 1.7, the runtime maintains a separate short list of such goroutines. This removes the need to look through the entire list of goroutines while user code is paused, and greatly reduces the number of memory accesses that can trigger the kernel’s NUMA-related memory migration code.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论