Go Context Cancel: Goroutine Not Stopping
In this tutorial, you'll learn about Go Context Cancel: Goroutine Not Stopping. We cover key concepts, practical examples, and best practices.
Context cancellation -- Use contexts to propagate cancellation signals and stop goroutines cleanly.
The Problem
Creating a cancellable context does not automatically stop goroutines. The goroutine must check ctx.Done() to know when to stop.
Wrong
ctx, cancel := context.WithCancel(context.Background())
go func() {
for {
time.Sleep(1 * time.Second)
fmt.Println("Working...") // Never stops!
}
}()
cancel() // Goroutine ignores cancellation!
Output:
// Goroutine runs forever despite cancel()
Right
ctx, cancel := context.WithCancel(context.Background())
go func() {
for {
select {
case <-ctx.Done():
fmt.Println("Stopping")
return
default:
time.Sleep(1 * time.Second)
fmt.Println("Working...")
}
}
}()
cancel() // Goroutine stops!
Output:
Working...
Working...
Stopping
Prevention
- Always check ctx.Done() in select statements
- Pass context to blocking operations
- Use default case in select for non-blocking work
- Call cancel() to release context resources
- Use defer cancel() immediately after WithCancel
Common Mistakes with context cancel
- Using
returnto exit a function early instead of wrapping a pure value in the monad - Mixing let bindings with <- bindings in do notation, producing type errors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro