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.
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)
}
go run .
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.
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.
Check this idea later
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?
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.
Sign in to keep your read marks on every device. Sign in
Was this helpful?