How to Gracefully Cancel Goroutines Using Go’s Context Package
This guide explains how to use Go's context package to send cancellation signals, create a cancellable context, run a task in a separate goroutine, and cleanly stop it from the main routine when certain conditions are met.
In Go development, when you need to terminate related goroutines after completing certain tasks, the context package provides a clean way to broadcast cancellation signals to one or more goroutines, allowing you to control their lifecycle.
Example Code
package main
import (
"context"
"fmt"
"time"
)
func main() {
// Create a cancellable context and its cancel function
ctx, cancel := context.WithCancel(context.Background())
// Run a task in a new goroutine
go func(ctx context.Context) {
for {
select {
case <-ctx.Done():
fmt.Println("goroutine cancelled")
return
default:
// Simulate work
fmt.Println("goroutine is working...")
time.Sleep(1 * time.Second)
}
}
}(ctx)
// Simulate main routine work
time.Sleep(3 * time.Second) // assume main does work for 3 seconds
// Now cancel the goroutine
fmt.Println("preparing to cancel goroutine")
cancel() // send cancellation signal
// Give the goroutine time to react
time.Sleep(1 * time.Second)
fmt.Println("main program ends")
}The program first creates a context.WithCancel(context.Background()) which returns a new context object and a cancel function. Calling cancel() sends a signal on the context’s Done channel.
Inside the spawned goroutine, an infinite loop repeatedly checks ctx.Done(). When the cancel function is invoked, the Done channel receives a value, the select case triggers, and the goroutine exits the loop and returns.
In the main function, after simulating some work with time.Sleep, the cancel function is called to stop the goroutine. The goroutine observes the cancellation signal via ctx.Done() and terminates gracefully.
Using the context package for goroutine cancellation is a common pattern in Go concurrent programming, offering an elegant mechanism for managing and stopping goroutines when needed.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Ops Development & AI Practice
DevSecOps engineer sharing experiences and insights on AI, Web3, and Claude code development. Aims to help solve technical challenges, improve development efficiency, and grow through community interaction. Feel free to comment and discuss.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
