gpt4 book ai didi

go - 为什么 goroutines 比其他语言的线程便宜很多?

转载 作者:IT王子 更新时间:2023-10-29 01:27:28 24 4
gpt4 key购买 nike

在他的演讲中 - https://blog.golang.org/concurrency-is-not-parallelism , Rob Pike 说 go routines 类似于线程但是便宜得多。谁能解释一下为什么?

最佳答案

参见“How goroutines work”。
它们在以下方面更便宜:

  • 内存消耗:
    线程以大内存开始,而不是几 Kb。
  • 安装和拆卸成本
    (这就是为什么你必须维护一个线程池)
  • 转换成本
    线程被抢占式调度,在线程切换期间,调度器需要保存/恢复所有寄存器。
    与 Go 不同,运行时在从创建到调度再到拆卸的整个过程中管理 goroutine。并且要保存的寄存器数量更少。

此外,如“Go’s march to low-latency GC”中所述,当运行时负责管理 goroutine 时,GC 更容易实现:

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.

关于go - 为什么 goroutines 比其他语言的线程便宜很多?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41906357/

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