Work that runs on its own needs a way to be stopped. A user closes the page, a server shuts down, or a deadline passes, and every goroutine still working on that request should give up instead of finishing work nobody will read. The context package is Go's standard way to carry that signal. A context.Context is passed as the first argument to every function that might wait, and its Done() channel is closed when the work should stop. Err() then says why: context.Canceled or context.DeadlineExceeded.
You create contexts from a parent. context.Background() is the root for a whole program. context.WithCancel(parent) returns a child and a cancel function that closes its Done channel, and context.WithTimeout(parent, d) closes it automatically after d. Cancelling a parent cancels all its children.
Two channel tools are new here. A select statement looks like a switch whose cases are channel sends or receives: it waits until one of them can proceed, runs that case and skips the rest. A buffered channel, made with make(chan T, n), holds up to n values, so a send completes at once while there is room, even with no receiver waiting yet. The example below uses a buffer of 1 so main can put a value in the channel before anyone reads it.
Predict and run
wait returns whichever happens first: a value arrives, or the context is done. What do the three calls return?
package main
import (
"context"
"fmt"
"time"
)
func wait(ctx context.Context, ready <-chan string) (string, error) {
select {
case v := <-ready:
return v, nil
case <-ctx.Done():
return "", ctx.Err()
}
}
func main() {
ready := make(chan string, 1)
ready <- "parsed"
fmt.Println(wait(context.Background(), ready))
ctx, cancel := context.WithCancel(context.Background())
cancel()
fmt.Println(wait(ctx, make(chan string)))
ctx, cancel = context.WithTimeout(context.Background(), 20*time.Millisecond)
defer cancel()
fmt.Println(wait(ctx, make(chan string)))
}Check your prediction
parsed <nil>
context canceled
context deadline exceededIn the first call the buffered channel already holds a value, so its case can proceed at once. In the other two, nothing is ever sent on the fresh channels, so only the context can end the wait. Always call cancel, even after a timeout: it releases the context's resources, and go vet warns when a cancel function is lost.
When both cases are ready
If several cases of a select can proceed at the same moment, Go picks one at random. That matters for cancellation. A worker pool whose send loop selects between "send the next job" and "the context is done" may keep sending for a while after cancellation, if a worker happens to be ready each time. The fix is not in the select but after it: check ctx.Err() once all the workers have stopped, and report cancellation however far the loop got. The project's pool ends exactly this way.
package main
import (
"context"
"fmt"
"sync"
)
func mapConcurrent[T, R any](ctx context.Context, items []T, workers int, f func(T) R) ([]R, error) {
workers = max(1, min(workers, len(items)))
results := make([]R, len(items))
jobs := make(chan int)
var wg sync.WaitGroup
for range workers {
wg.Add(1)
go func() {
defer wg.Done()
for i := range jobs {
results[i] = f(items[i])
}
}()
}
send:
for i := range items {
select {
case jobs <- i:
case <-ctx.Done():
break send
}
}
close(jobs)
wg.Wait()
if err := ctx.Err(); err != nil {
return nil, err
}
return results, nil
}
func main() {
double := func(n int) int { return n * 2 }
fmt.Println(mapConcurrent(context.Background(), []int{1, 2, 3}, 2, double))
ctx, cancel := context.WithCancel(context.Background())
cancel()
fmt.Println(mapConcurrent(ctx, []int{1, 2, 3}, 2, double))
}[2 4 6] <nil>
[] context canceledbreak send leaves the labelled for loop; a plain break would only leave the select. After cancellation the function still closes jobs and waits for the workers, so no goroutine is left running when it returns. Then the final check makes the answer deterministic: cancelled means no results, however many jobs slipped through.
Rules for passing contexts
Pass the context as the first parameter, named ctx, and pass it down to everything that may wait. Do not store it in a struct, where it would outlive the request it belongs to. Use context.Background() only at the top: in main, as the project does, or in a test. The project's checks pass an already cancelled context to run and expect context.Canceled and no output, which proves cancellation reaches all the way through.
Cancellation is cooperative
Cancelling a context does not stop a goroutine by force. It only closes a channel. Each function that might wait must check ctx.Done() or ctx.Err() itself, and a long calculation that never checks will run to the end. That is why the pool checks between jobs.
Practice
Your turn
Write sendAll(ctx context.Context, items []string, out chan<- string) (int, error), which sends items until they run out or the context is done, and returns how many it sent. Start a receiver goroutine that collects items, calls cancel after the third, and stops receiving. Print the count, the error and the received items. Then call sendAll with a fresh context and a receiver that takes everything.
The output should be:
3 context canceled [tent drill lamp]
5 <nil> [tent drill lamp hat rope]package main
func main() {
// Write sendAll, then try it with a receiver that cancels after three items.
}Hint 1: the idea
Once the receiver has stopped, nobody can take another item, so the only case left that can proceed is <-ctx.Done(). That makes the count predictable.
Hint 2: a first step
Inside the loop, select between case out <- item: sent++ and case <-ctx.Done(): return sent, ctx.Err(). Close out when everything has been sent, so the second receiver's range ends.
Worked solution
package main
import (
"context"
"fmt"
"sync"
)
func sendAll(ctx context.Context, items []string, out chan<- string) (int, error) {
sent := 0
for _, item := range items {
select {
case out <- item:
sent++
case <-ctx.Done():
return sent, ctx.Err()
}
}
close(out)
return sent, nil
}
func main() {
items := []string{"tent", "drill", "lamp", "hat", "rope"}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
out := make(chan string)
var got []string
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
for item := range out {
got = append(got, item)
if len(got) == 3 {
cancel()
return
}
}
}()
sent, err := sendAll(ctx, items, out)
wg.Wait()
fmt.Println(sent, err, got)
all := make(chan string)
var everything []string
wg.Add(1)
go func() {
defer wg.Done()
for item := range all {
everything = append(everything, item)
}
}()
sent, err = sendAll(context.Background(), items, all)
wg.Wait()
fmt.Println(sent, err, everything)
}3 context canceled [tent drill lamp]
5 <nil> [tent drill lamp hat rope]The first sender stopped after three items because the receiver cancelled and left. The second ran to the end and closed its channel, which ended the receiver's range. got and everything are read only after wg.Wait(), so each is read after its goroutine has finished writing it.
Completion is saved in this browser only. It does not measure mastery.