Principal
How did you deal with goroutine leak — did you monitor it?
sobes.tech AI
Answer from AI
A goroutine leak occurs when goroutines remain in a waiting or blocked state and do not terminate, leading to memory and resource leaks. To combat this, it is important to:
- Use contexts (
context.Context) to manage the lifetime of goroutines and cancel their work. - Monitor channels: close them properly and avoid blocking when sending/receiving.
- Monitor the number of active goroutines using
runtime.NumGoroutine(). - Use profiling with
pprofto identify goroutines that do not terminate.
Example of monitoring the number of goroutines:
package main
import (
"fmt"
"runtime"
"time"
)
func main() {
go func() {
select {} // blocking goroutine
}()
time.Sleep(time.Second)
fmt.Printf("Active goroutines: %d\n", runtime.NumGoroutine())
}
Regular monitoring and profiling help to detect and eliminate goroutine leaks in a timely manner.