ProgramGuru

Context Cancellation

Start with Context Cancellation

In this lesson, explore context cancellation through one small Go program, and connect its output to the language rules behind it.

What you’ll learn

  • Explain the main purpose of context cancellation.
  • Read and run the complete Go example in this lesson.
  • Apply the concept and recognize common mistakes.

Understand the idea

context.WithCancel creates a child context plus a cancellation function. Call the function when the work is no longer needed; goroutines should watch Done() or call cancellation-aware APIs.

Cancellation is cooperative: it signals the worker but does not forcibly terminate it. Deferred cleanup and explicit shutdown rules remain important.

Visualize how it works

Follow this diagram before executing the example. Check where a value or decision changes what runs next.

Visual explanation for cancelCancellation is a signal that participants must handle.Create child contextStep 1Start workerStep 2Call cancelStep 3Observe DoneStep 4Cancellation is a signal that participants must handle.
Cancellation is a signal that participants must handle.

Run a complete Go example

This example is a complete program. Save it as main.go or paste it into the Go Playground.

Go code

package main

import (
	"context"
	"fmt"
)

func main() {
	ctx, cancel := context.WithCancel(context.Background())
	cancel()
	<-ctx.Done()
	fmt.Println("Canceled:", ctx.Err() == context.Canceled)
}

Output

Canceled: true

Trace what the program does

Calling cancel closes the Done channel and sets the context error to context.Canceled. The receive returns immediately.

Avoid common mistakes

  • Forgeting cancel can retain resources until other cleanup occurs.
  • A task must observe cancellation for it to have practical effect.

Try it yourself

Write a worker that selects between a work channel and ctx.Done, then trigger cancel.

Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.

Check your understanding

How does a goroutine learn its context was canceled?
Choose one answer. You can try again.

Answer and explanation

Its Done channel becomes ready

Correct. Calling cancel closes the Done channel and sets the context error to context.

What you should remember

You have practiced Context Cancellation in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.

Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Mutexes →