Release timers and cancellation resources
Release timers and cancellation resources
Cancellation is also resource ownership. The caller that derives a cancelable context should arrange for its cancel function to run on every return path. This releases the parent’s reference and stops associated timers when applicable. Use defer in the function that owns the context, not in a long-running loop where defers accumulate until the function returns.
package main
import ( "context" "fmt" "time")
func job(parent context.Context) context.Context { ctx, cancel := context.WithTimeout(parent, time.Hour) defer cancel() return ctx}func main() { ctx := job(context.Background()) <-ctx.Done() fmt.Println(ctx.Err() == context.Canceled)}This small demonstration returns a canceled context solely to inspect cleanup; ordinary application code should finish the context-owned work inside the function before returning. Do not return a context that a deferred cancel will invalidate if callers expect it to remain active. When ownership is transferred, transfer the cancel function explicitly too.
Expected output:
trueOwn a timer while waiting
package main
import ( "context" "fmt" "time")
func wait(ctx context.Context, d time.Duration) error { timer := time.NewTimer(d) defer timer.Stop() select { case <-ctx.Done(): return ctx.Err() case <-timer.C: return nil }}func main() { ctx, cancel := context.WithCancel(context.Background()) defer cancel() cancel() fmt.Println(wait(ctx, time.Hour) == context.Canceled) fmt.Println(wait(context.Background(), 0) == nil)}The timer is stopped on either path. With a canceled context and a one-hour timer the cancellation path is expected; with a root context and a zero timer the timer path is ready eventually. This timer is discarded, not reset or reused. Reusable timer channels have version-dependent Stop/Reset rules (see Time and Scheduling); do not blindly drain a timer channel after Stop. Cancellation and stopping a timer do not wait for other goroutines or AfterFunc callbacks to finish; use a separate completion signal when necessary.
Expected output:
truetrueTry it locally
Write a function attempt(parent context.Context) error that derives a cancellable context, defers cancel, and receives from Done of an already-canceled parent through its child. Print whether the returned error equals context.Canceled.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Select and cancellation 08: Release timers and cancellation resources
Check the lesson objective before moving on.
When should an owned CancelFunc be called?
Does stopping a timer wait for an AfterFunc callback already running?