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.
Think of this as a remote control for your running code. You create a context that acts like a shared signal wire, and you get a button (the cancel function) to cut the power. When you press that button, every part of your program listening to that signal stops working immediately, allowing you to shut down tasks cleanly without waiting for them to finish on their own.