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

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

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

问题

package main

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

func main() {
	// time.Sleep(100 * time.Millisecond)//通过添加此行,goroutine的数量会增加
	fmt.Println(runtime.NumGoroutine())
}

我正在尝试找出程序中的goroutine数量。我的代码在这里。在编写代码时,我注意到默认的goroutine数量是4。

对我来说:

  • main函数是一个goroutine
  • 垃圾回收器是一个goroutine

其他的是什么?

通过添加上面的time.Sleep,goroutine的数量增加到了5。这是什么原因呢?

英文:
package main

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

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

I am trying to find out the number of goroutines in a program. My code is here. While coding this I noticed default number of goroutines is 4.

For me:

  • main is one goroutine
  • garbage collector is one goroutine

What are the others?

By adding the time.Sleep (above), the number of goroutines increases to 5. What is the reason for this?

答案1

得分: 5

实际上,内存管理需要多个goroutine...

最初的4个goroutine包括:

  • 主goroutine
  • 后台清扫器(并发垃圾回收的阶段)
  • 清扫器(也是垃圾回收器的一部分)
  • 最终器goroutine(专门运行最终器,最终器附加到对象上)

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

因此,最终你会有5个goroutine。

英文:

Actually, memory management takes more than one goroutine ...

The 4 initial goroutines are:

  • the main goroutine
  • the background sweeper (the phase of the garbage collection which is concurrent)
  • the scavenger (also part of the garbage collector)
  • the finalizer goroutine (exclusively running the finalizers eventually attached to objects)

Then, the time.Sleep function is called. It requires a timer. Timers are implemented in the runtime, through an additional goroutine (timerproc), which processes events stored in the timer heap. This goroutine is lazily started when the first timer is added to the heap.

Hence, you finally get 5 goroutines.

huangapple
  • 本文由 发表于 2015年1月4日 15:43:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/27763501.html
匿名

发表评论

匿名网友

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

确定