← Runtimes
Runtimes

Go select, sync, and context

Choose a ready channel operation, and give owned work a way to finish.

Owning goroutines means coordinating their waits, cancellation and completion.

Outcome

Use select to wait on several events, prevent goroutine leaks from abandoned channel operations, and propagate cancellation through derived contexts.

Terminology (6)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

select
Chooses a channel operation that can proceed. If several cases are ready, one is chosen by uniform pseudo-random selection. default runs only when no communication can proceed.
Goroutine leak
A goroutine blocked or running forever after nobody needs it, holding its stack and anything it references.
context.Context
Carries cancellation, deadlines and request values through calls. A cancellable context closes Done on cancellation; Background has no deadline and a nil Done channel.
Derived context
A child made from a parent with WithCancel, WithTimeout or WithDeadline. Parent cancellation propagates to it; a child deadline can expire earlier. Canceling a child does not cancel its parent.
sync.WaitGroup
Coordinates a task counter; Wait returns after the matching Done calls reduce it to zero. It does not intrinsically know when a goroutine exits.
sync.Mutex
Lets one goroutine at a time into a critical section.

Waiting, stopping and finishing

A goroutine can outlive the function that launched it. Returning a useful result therefore does not establish that the operation’s remaining work has finished. Its owner must account for what each goroutine can still be waiting on, which event can let it stop, and how completion is observed.

Go separates these responsibilities. select coordinates channel operations that can proceed; context carries deadlines and cancellation through calls; sync provides completion counters and mutual exclusion. Compose them around the operation’s lifetime: a cancellation signal has to reach the relevant wait, and requesting cancellation does not itself wait for goroutines to exit.

01Waiting on several things

select chooses among operations that can proceed

A downloader asks three mirrors and uses the first answer. It returns quickly, but its memory keeps growing: every request leaves goroutines behind, some blocked forever, others still downloading long after anyone cares. How do goroutines wait, coordinate and stop?

A plain <-answers waits for a value or channel closure. A select can also include a timer or ctx.Done, making those events able to end this channel wait. If multiple cases are ready, it selects one uniformly pseudo-randomly; it gives no inherent priority to cancellation or the earliest wall-clock event. It cannot interrupt unrelated blocking code. WaitGroup coordinates completion counts; Mutex protects shared-state invariants.

02Goroutine leaks

A send that nobody receives blocks forever

This program starts two senders, keeps the first value and returns, first with an unbuffered channel and then with a buffered one, and counts the goroutines still alive 50 ms later.

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
package main

import (
	"fmt"
	"runtime"
	"time"
)

// first starts two senders and keeps only the first value it receives.
func first(results chan string) string {
	go func() { results <- "fast" }()
	go func() {
		time.Sleep(10 * time.Millisecond)
		results <- "slow"
	}()
	return <-results
}

func main() {
	baseline := runtime.NumGoroutine()

	first(make(chan string))
	time.Sleep(50 * time.Millisecond)
	fmt.Printf("unbuffered: %d goroutine(s) left\n", runtime.NumGoroutine()-baseline)

	baseline = runtime.NumGoroutine()
	first(make(chan string, 2))
	time.Sleep(50 * time.Millisecond)
	fmt.Printf("buffered: %d goroutine(s) left\n", runtime.NumGoroutine()-baseline)
}
terminal.sh
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
go run .
The recorded probe printed process-wide goroutine deltas after its 50 ms waits. Which pair was observed? Assume the illustrated sends have reached their shown states; this is not a count guaranteed for arbitrary scheduling.

03Context propagation

Cancellation reaches only what derives from it

Cancellation propagates down a context tree; code must still observe it. A helper that derives only from Background ignores its caller’s deadline. Derive an attempt’s timeout from the supplied search context, then release that attempt’s timer with its cancel function. Canceling the search after a winner must also reach the losing attempts. A separate per-mirror timeout is a failure of that attempt, not a successful mirror response; another attempt may still succeed.

A handler’s context expires at 200 ms. Its helper derives a five-second context from Background and passes it to a query. Assume the query remains pending until that supplied context expires and cooperatively notices it, ignoring extra scheduling delay. When can it stop?

04Practice

Search the mirrors

The lab models mirror delays with native sleeps/timers; it makes no network requests. Its supplied launch wrapper counts unfinished mirror tasks at launch/return boundaries. The output label goroutines left refers to that owned-work receipt, not all runtime goroutines. It samples 150 ms after search returns. Fastest-response and deadline checks assume the declared separated timings and ordinary scheduling; they are not operating-system latency guarantees.

The mirror search

Ask several mirrors at once, take the first answer, and leave nothing behind: give up at the deadline, fix leaking senders, then cancel slow fetches through the context.

  1. easy · R-GOSEL-V4-1 Answer or give up
  2. medium · R-GOSEL-V4-2 Leave nothing behind
  3. hard · R-GOSEL-V4-3 Cancel what you started
Check this idea later
Code does result := <-ch and the producer may never send. How do you stop waiting after 2 seconds?
A function starts five goroutines that each send on an unbuffered channel, reads one value and returns. What happens to the other four?
Which call derives a child cancellation signal from its caller’s ctx, so an operation that cooperatively watches it can stop?
Sources
In the frontend An operation timeout is not automatically linked to its caller. Optional

A mirror-preview helper is shared by a Next route and a SvelteKit handler. Each caller passes its operation’s AbortSignal. Assume that signal is already aborted when the helper starts, and that fetch honors whichever signal it receives.

The helper creates a fresh five-second timeout signal for fetch. Which request can cancel this fetch, and does accepting callerSignal as a parameter establish any relationship by itself?

lib/read-mirror.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
export async function readMirror(url: string, callerSignal: AbortSignal) {
  const attempt = AbortSignal.timeout(5000);
  const response = await fetch(url, { signal: attempt });

  return response.text();
}

This helper is under review. callerSignal is unused, so its already-aborted state does not cancel the fetch. The local timeout supplies a separate lifetime; no HTTP server behavior or automatic propagation is assumed.

Sources: DOM standard: AbortSignal timeout and combination.

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.