How do I avoid goroutine leaks in Go?

In Go, goroutine leaks can occur when you create goroutines that are not properly terminated, leading to memory leaks and resource exhaustion. Here are some strategies to avoid goroutine leaks:

Use Context to Control Goroutines

Using the context package allows you to signal cancellation to goroutines, which helps in cleaning up resources when they are no longer needed.

package main import ( "context" "fmt" "time" ) func worker(ctx context.Context) { for { select { case <-ctx.Done(): fmt.Println("Worker stopping") return default: // Simulate work time.Sleep(1 * time.Second) fmt.Println("Doing work...") } } } func main() { ctx, cancel := context.WithCancel(context.Background()) go worker(ctx) // Simulate running for 5 seconds time.Sleep(5 * time.Second) cancel() // Signal the worker to stop time.Sleep(1 * time.Second) // Give time for the worker to finish }

Limit the Number of Goroutines

Using a worker pool can help limit the number of active goroutines.

Proper Error Handling

Ensure that errors are handled properly, especially in goroutines. Ignoring errors could lead to unwanted behavior.

Use WaitGroups to Wait for Goroutines

Utilize sync.WaitGroup to wait for goroutines to complete before exiting the main function.

Review Your Code

Regularly review your code for goroutines that might not exit properly under certain conditions.


Goroutine leaks Go programming context package memory management worker pool error handling