← All Exercises

Go Context Cancellation

advancedgo~30min

Background

Context provides cancellation signals and deadlines across API boundaries and goroutine trees in Go.

Problem

Write a Go function that performs a long-running computation with context cancellation support, stopping early when the context is cancelled.

Input

A context.Context and a number of iterations to simulate work.

Output

Results computed before cancellation, or an error if cancelled.

Sample tests

Sample 1

Input: context with 1s timeout, 100 iterations
Expected: all results (completed before timeout)

Your solution

Learning objective

Learn context cancellation, the select pattern for cancellation checks, and deadline propagation.