Go is a feature that is automatically recycled with memory, so memory is generally not compromised. However, there is a leak in the goroutine, and the leaked goroutine reference memory cannot be recycled.
In the following program, the background goroutine enters the natural number sequence to the pipeline, and the output sequence is in the main function. But when break jumps out of the for loop, the background goroutine is in a state that cannot be reclaimed.
Func Main () { ch: = func () <-chan int { ch: = make (chan int) go func () {for I: = 0;; i++ { ch < ;-I } } () return ch } () for V: = Range ch { FMT. Println (v) if v = = 5 {break }} }
We can avoid this problem through the context package:
Func Main () { ctx, Cancel: = context. Withcancel (context. Background ()) ch: = func (CTX context. Context) <-chan int { ch: = make (chan int) go func () {to I: = 0;; i++ { Select {case <-ctx. Done (): return case ch <-i: } } } () return ch } (CTX) for V: = Range ch { Fmt. Println (v) if v = = 5 { cancel () Break }} }
When the main function jumps out of the loop, it notifies the background goroutine to exit by calling Cancel (), thus avoiding goroutine leaks.
Go use context pack to avoid goroutine leaks