A goroutine leak occurs when a goroutine is started but never terminates, holding onto memory and CPU resources indefinitely. This usually happens when a goroutine blocks forever on a channel send or receive with no corresponding operation, or when a loop lacks an exit condition. To prevent leaks, ensure every go statement has a clear termination path, often by using context.Context to signal cancellation or by closing channels to unblock waiting receivers.
ctx, cancel := context.WithCancel(context.Background())
// Start goroutine with context
wg.Add(1)
go func() {
defer wg.Done()
for {
select {
case <-ctx.Done():
return // Exit immediately on cancellation
case data := <-inputChan:
process(data)
}
}
}()
// Later: cancel to stop the goroutine
cancel()
wg.Wait()