Consider the following code as a simplified example:
func printer(c <-chan int) {
for {
fmt.Print(<-c)
}
}
func provide() {
c := make(chan int)
go printer(c)
for i := 1; i <= 100; i++ {
c <- i
}
}
The function provide
creates a go routine printer
that prints the data provide
generates.
My question is, what happens after provide
returns and printer
starts blocking on the empty channel. Will the go routine leak, as there is no further reference to c
or will the garbage collector catch this case and dispose both the go routine and c
?
If it is indeed the case that this kind of code causes a memory leak, what strategies can I do to prevent such a memory leak from happening?