doudao2407
2015-01-04 07:43
浏览 292
已采纳

默认情况下,Go程序中启动了多少个goroutine?

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?

图片转代码服务由CSDN问答提供 功能建议

 包main 
 
import(
 //“时间” 
“运行时” 
  “ fmt” 
)
 
func main(){
 //time.Sleep(100 * time.Millisecond)//通过添加此goroutine数量会增加
fmt.Println(runtime.NumGoroutine())
  } 
   
 
 

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

对我来说:

  • main是一个goroutine
  • 垃圾收集器是一个goroutine

    还有哪些?

    通过添加时间 .sleep (上面),goroutine的数量增加到5。这是什么原因?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duanpi2033 2015-01-04 09:23
    已采纳

    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.

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题