Context WithCancel

Create a cancellable context using context.WithCancel to stop goroutines immediately by calling the returned cancel function.

Use context.WithCancel to create a cancellable context that stops goroutines when a specific condition is met.

ctx, cancel := context.WithCancel(context.Background())
// Use ctx in your goroutines
// Call cancel() when you want to stop them

The cancel function signals all goroutines using ctx to stop immediately. Always call cancel() when the work is done or an error occurs to prevent resource leaks.