vrbilgi
vrbilgi

Reputation: 5803

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())
}

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:

What are the others?

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

Upvotes: 4

Views: 1285

Answers (1)

Didier Spezia
Didier Spezia

Reputation: 73306

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.

Upvotes: 5

Related Questions