一个 Go 程序默认启动了多少个 goroutine?

How many goroutines are started by default in a Go program?

package main

import (
    //"time"
    "runtime"
    "fmt"
)

func main() {
    //time.Sleep(100 * time.Millisecond)//By adding this number of goroutine increases
fmt.Println(runtime.NumGoroutine())
}

我正在尝试找出程序中的 goroutines 数量。我的code is here。在编码时我注意到 goroutines 的默认数量是 4.

对我来说:

其他的是什么?

通过添加time.Sleep(上图),goroutine的数量增加到5个,这是什么原因?

其实内存管理需要不止一个goroutine ...

4 个初始 goroutine 是:

  • 主 goroutine
  • 后台清扫器(并发的垃圾收集阶段)
  • 清道夫(也是垃圾收集器的一部分)
  • finalizer goroutine(独占运行 finalizers 最终附加到对象)

然后,调用time.Sleep函数。它需要一个计时器。定时器是在运行时通过一个额外的 goroutine (timerproc) 实现的,它处理存储在定时器堆中的事件。当第一个定时器被添加到堆中时,这个 goroutine 被延迟启动。

因此,你最终得到了 5 个 goroutine。