Skip to content

Go Context Cancel: Goroutine Not Stopping

DodaTech Updated 2026-06-24 1 min read

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()
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

  1. Using return to exit a function early instead of wrapping a pure value in the monad
  2. Mixing let bindings with <- bindings in do notation, producing type errors
  3. 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

**Can I cancel from multiple goroutines?**

Yes. cancel() is safe to call from multiple goroutines.

What happens to child contexts when parent is cancelled?

All children are cancelled too.

Should I pass context by value?

Yes. Context is designed to be passed by value.


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