I'm reading this blog, https://medium.com/golangspec/goroutine-leak-400063aef468, and have adapted the following example illustrating a goroutine leak due to receiving from a nil channel:
package main
import (
"flag"
"fmt"
"runtime"
"time"
)
var initChannel bool
func main() {
flag.Parse()
var ch chan int
if initChannel {
ch = make(chan int, 1)
ch <- 1
}
go func(ch chan int) {
<-ch
}(ch)
c := time.Tick(1 * time.Second)
for range c {
fmt.Printf("#goroutines: %d\n", runtime.NumGoroutine())
}
}
func init() {
flag.BoolVar(&initChannel, "init", false, "initialize channel")
}
I've noticed that if I run it with initChannel
false
, the number of goroutines is 2:
> go run main.go
#goroutines: 2
#goroutines: 2
whereas if I run it with true
, the number is 1:
> go run main.go --init
#goroutines: 1
#goroutines: 1
I don't quite understand why this is the case, however. I only see one go
statement, so I would expect only one goroutine in either case. Why are there two goroutines when reading from a nil channel?