Skip to content

select: Multiplexing, Non-Blocking Ops, Timeouts, for-select ​

"If one or more of the communications can proceed, a single one that can proceed is chosen via a uniform pseudo-random selection. Otherwise, if there is a default case, that case is chosen. If there is no default case, the "select" statement blocks until at least one of the communications can proceed." — The Go Programming Language Specification, "Select statements"

Summary: select waits on several channel operations at once and runs exactly one: a random one among those that are ready, the default case if none is ready, or it blocks until one becomes ready. Every timeout, cancellation, heartbeat, non-blocking send, fan-in and graceful-shutdown loop in Go is built from that one rule plus two facts about channels: a nil channel is never ready and a closed channel is always ready. Focus: the evaluation steps of select, random choice among ready cases, default for non-blocking send and receive, nil channel cases, closed channel cases, time.After versus time.NewTimer with Timer.Stop/Timer.Reset, context.WithTimeout and ctx.Done, for { select {} } loops and their exits, the busy loop, heartbeats with time.Ticker and Ticker.Reset, priority select, quit channels, fan-in, bounded send with drop-on-full, select {}, reflect.Select, fairness and starvation, deadlock reports, draining after cancellation, sync.Cond versus channels, errgroup, and the PHP equivalents (stream_select, ReactPHP, Swoole). Learning goal: Read any select and say which case can run and when it blocks; write a worker loop that has a timeout, a heartbeat and a clean shutdown without leaking a goroutine or a timer; and pick drop, wait-with-timeout or backpressure for a full channel on purpose.

This page owns the select statement and the loops built around it. Neighbours are linked, not re-taught: channel creation, buffering, direction and close are in Goroutines & Channels; how a context.Context is created, propagated and carries values is in context: Cancellation, Deadlines, Values; Timer and Ticker themselves (resolution, AfterFunc, the Go 1.23 change in full) are in time.Time, Formatting/Parsing, Time Zones, Timers; sync.Cond, Mutex and WaitGroup are in sync & atomic; worker pools, pipelines and errgroup limits are in Worker Pools, Pipelines, Fan-Out/Fan-In, errgroup; the race detector and deadlock theory are in Race Conditions, the Race Detector, Deadlocks; reflect in general is in reflect: When and How; OS signals and process shutdown are in OS Processes, Signals & Graceful Shutdown.

Facts below come from the Go specification (the "Select statements", "Receive operator", "Send statements" and "Close" sections), Effective Go, the Go FAQ, the Go Memory Model, the Go blog posts "Go Concurrency Patterns: Timing out, moving on" (2010) and "Go Concurrency Patterns: Pipelines and cancellation" (2014), the talks "Go Concurrency Patterns" (Pike, 2012) and "Advanced Go Concurrency Patterns" (Ajmani, 2013), the Go 1.23, 1.26 and 1.27 release notes, the runtime source runtime/select.go, and package documentation printed by go doc on Go 1.27.4 (the toolchain on the machine that wrote this page; pkg.go.dev returns HTTP 403 to scripted clients). Snippets live in one module with go 1.24.0 in go.mod; they pass gofmt, go vet and go test -race.

Page map ​

If you are looking forGo to
Tables you can memorise in one minuteEverything in one minute
Why Go has select at allWhy it exists
CSP, Newsqueak and the 2010 timeout postWhere it comes from
A before/after of a stuck receiveGo
The exact steps a select takesThe select statement
Two cases ready, which one runsRandom selection among ready cases
default, try-send, try-receiveNon-blocking send and receive
ch = nil to switch a case offNil channel cases
A loop that spins on a closed channelClosed channel cases
time.After, one wait with a limitTimeouts with time.After
Timer leaks, NewTimer, Stop, ResetTimers in loops
context.WithTimeout, ctx.Done()Cancellation with ctx.Done
for { select {} }, how to leave itThe for-select loop
default inside a loop eating a CPUThe busy loop
Heartbeats, time.Ticker, Ticker.ResetHeartbeats and tickers
One channel must win over anotherPriority select
quit channels, chan chan error, contextQuit channels versus context
Merging many channelsFan-in with select
Full channel: drop, wait or give upBounded send
select {}Blocking forever
A run-time number of channelsreflect.Select
Fairness, starvation, hot channelsFairness and starvation
Leftovers after cancellationDraining
close as a broadcast, sync.CondClosing versus signalling, sync.Cond
errgroup and selecterrgroup with select
fatal error: all goroutines are asleep - deadlock!Error texts
What the runtime does underneathInside the runtime
What a select costsBenchmarks
Graceful shutdown worker, end to endSolving the classic problems
Which pattern for which jobChoosing
One process to many servicesIn architecture
Run it yourselfLab
stream_select, ReactPHP, SwooleFor PHP/Laravel developers

Everything in one minute ​

FormPlain wordsTiny exampleGotcha
select with casesWait for whichever channel is ready firstselect { case v := <-a: ...; case b <- x: ... }All operands are evaluated even for cases that lose
Two ready casesGo flips a fair coinboth channels have dataNever write code that relies on source order
default"If nothing is ready right now"select { case v := <-c: ...; default: }Inside a for, it turns waiting into spinning
non-blocking sendSend only if it will not waitcase c <- v: default:Still panics on a closed channel
non-blocking receiveTake a value only if one is therecase v, ok := <-c: default:ok == false means closed, not empty
nil channel caseA case that can never runa = nilAll nil and no default blocks forever
closed channel caseA case that can always runclose(done)Unread, it wins every loop iteration
time.After(d)A channel that fires once after dcase <-time.After(time.Second):In a loop it restarts every iteration
time.NewTimer(d)A timer you can Stop and Resett.Reset(idle)Create once, reuse in the loop
ctx.Done()Closed when the context endscase <-ctx.Done(): return ctx.Err()ctx.Err() says why
for { select {} }An event loop in one goroutineworker, poller, server loopbreak leaves only the select
time.TickerRepeating tick channelheartbeat every 10 sSlow readers lose ticks
select {}Block this goroutine foreverend of main in a serverDeadlock if nothing else runs
reflect.Selectselect over a slice of casesdynamic fan-inSlower, allocates, max 65536 cases
Channel stateReceive in a caseSend in a caseClose
nilnever readynever readypanic: close of nil channel
open, empty, no sendernot readyready if a receiver waits or buffer has roomok
open with buffered datareadyready if buffer has roomok
closed, buffer drainedalways ready, zero value, ok == falseready, and the send panics: send on closed channelpanic: close of closed channel
Go versionWhat changed for this pageWhere
1.0select as specified today; random choice among ready casesThe select statement
1.1reflect.Select and reflect.SelectCasereflect.Select
1.7context in the standard library; ctx.Done() replaces ad-hoc quit channelsCancellation
1.15Ticker.ResetHeartbeats
1.22Loop variable per iteration: goroutines in for loops capture the right valueFan-in
1.23Timer and Ticker channels unbuffered; unreferenced timers collectable; no stale tick after Reset/Stop (go.mod 1.23+)Timers in loops
1.24testing.B.Loop used in the benchmarksBenchmarks
1.25testing/synctest generally available: test timeouts without sleepingSolving
1.26Experimental goroutineleak profileError texts
1.27goroutineleak profile generally available; asynctimerchan removed, time channels always synchronousTimers in loops
MistakeSymptomSection
time.After inside a for-select as an overall deadlineNever times out while messages keep comingTimers in loops
default in a waiting loopOne core at 100 % doing nothingThe busy loop
Not setting a closed channel to nilLoop spins on zero valuesClosed channel cases
break to leave a for-selectLoop keeps runningThe for-select loop
Expecting source order to give priorityLow-priority work runs first half of the timePriority select
Plain send with no ctx.Done() caseGoroutine leak when the reader leavesCancellation
Two default cases or a non-channel caseCompile errorError texts
select {} in a program with nothing else runningfatal error: all goroutines are asleep - deadlock!Blocking forever

Why it exists ​

A goroutine that does v := <-ch is stuck until ch delivers. Real programs never want only that: they want "a value, or give up after two seconds, or stop because the user left, or send a heartbeat meanwhile". Threads-and-locks languages answer with condition variables plus timed waits plus interrupt flags, each a separate API. Go answers with one statement that waits on several communications at once, and makes time and cancellation into channels (time.After, ctx.Done()) so they fit into the same statement.

Design choiceWhat you give upWhat you get
Timeouts are channels, not a parameter of receivech.Receive(timeout) convenienceAny number of timeouts, cancellations and data channels in one wait
Uniform random choice among ready casesPredictable source-order priorityNo case can starve another by position
default makes any select non-blockingA separate TryReceive APIOne syntax for blocking and polling
Nil channels are never readyA runtime error on a nil channelSwitch cases off by assignment
Closed channels are always ready"Closed" as an event that fires onceclose is a broadcast to every waiter, now and later
Only channel operations allowed in casesWaiting on a mutex or a sync.CondOne well-defined, deadlock-free locking order in the runtime

Everyday picture used through the page: a receptionist with several phones on the desk. select is "pick up whichever rings first; if two ring together, pick one without favouritism". default is "if nothing is ringing, go do paperwork". A timeout is a kitchen timer standing on the desk as just another phone that rings once. ctx.Done() is the manager's phone that rings when the office closes. A nil channel is a phone with its cable pulled out: it will never ring. A closed channel is a phone stuck ringing forever.

Three common misunderstandings, up front ​

  1. "Cases are checked top to bottom." They are evaluated top to bottom, but the case that runs is chosen at random among the ready ones. Priority needs code (Priority select).
  2. "default makes my loop efficient because it never blocks." It makes the loop never sleep. A for with a select that has default and nothing else to do is a busy loop.
  3. "A closed channel case fires once." It fires every time you select on it, forever. That is what makes close(done) a broadcast, and what makes forgetting ch = nil a spin.

Where it comes from ​

The Go FAQ traces Go's concurrency to Hoare's Communicating Sequential Processes: "Go's concurrency primitives derive from a different part of the family tree whose main contribution is the powerful notion of channels as first class objects", and names Newsqueak and Limbo among the influences. CSP's guarded alternative command is the ancestor of select. In the 2012 talk "Go Concurrency Patterns" Rob Pike summarised it as: "All channels are evaluated. Selection blocks until one communication can proceed, which then does. If multiple can proceed, select chooses pseudo-randomly. A default clause, if present, executes immediately if no channel is ready."

MilestoneYearPrimary source
"Go Concurrency Patterns: Timing out, moving on" (Andrew Gerrand): timeouts as a channel, non-blocking send with default2010go.dev/blog/concurrency-timeouts
reflect.Select addedGo 1.1, 2013go.dev/doc/go1.1
"Go Concurrency Patterns" talk (Rob Pike): quit channel, timeout for whole conversation2012go.dev/talks/2012/concurrency.slide
"Advanced Go Concurrency Patterns" (Sameer Ajmani): for-select loop, closing chan chan error, nil channels in cases2013go.dev/talks/2013/advconc.slide
"Pipelines and cancellation" (Sameer Ajmani): closing a done channel as a broadcast2014go.dev/blog/pipelines
Timer channels become synchronousGo 1.23, 2024go.dev/doc/go1.23
goroutineleak profile, generally availableGo 1.27go.dev/doc/go1.27

The 2010 post opens with the sentence that explains the whole design: "Although Go's channels do not support them directly, they are easy to implement." Its two examples (a timeout channel and the non-blocking send to a buffered result channel in Query) are still the two building blocks of every pattern on this page.

Go ​

Before ​

A handler waits for a result from a backend goroutine. If the backend is slow, the handler hangs; if the client disconnects, the handler still hangs; and the backend goroutine leaks because nobody will ever receive its send.

go
func handle(w http.ResponseWriter, r *http.Request) {
	res := make(chan Result) // unbuffered
	go func() { res <- callBackend() }() // blocks forever if handle has returned
	fmt.Fprint(w, <-res)                 // waits as long as the backend wants
}

After ​

The same wait as a select with the request context (which carries the client disconnect and any server deadline), and a result channel with one buffer slot so the backend goroutine can always finish its send and exit.

go
func handle(w http.ResponseWriter, r *http.Request) {
	ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
	defer cancel()
	res := make(chan Result, 1) // the sender never blocks, so it never leaks
	go func() { res <- callBackend(ctx) }()
	select {
	case v := <-res:
		fmt.Fprint(w, v)
	case <-ctx.Done():
		http.Error(w, ctx.Err().Error(), http.StatusGatewayTimeout) // "context deadline exceeded"
	}
}

The reusable pieces are in the timeouts snippet:

go
// Package timeouts shows the select timeout patterns: time.After for a
// single wait, ctx.Done for cancellation, one reusable Timer for an idle
// timeout, and a timer created once for an overall deadline.
package timeouts

import (
	"context"
	"errors"
	"time"
)

// ErrTimeout is returned when a wait gives up.
var ErrTimeout = errors.New("timeout waiting for value")

// ErrIdle is returned by IdleLoop when the input is silent for too long.
var ErrIdle = errors.New("idle timeout")

// RecvTimeout waits at most d for one value. time.After is fine for a
// single wait: the timer is collectable once the select returns (Go 1.23+).
func RecvTimeout[T any](ch <-chan T, d time.Duration) (T, error) {
	select {
	case v := <-ch:
		return v, nil
	case <-time.After(d):
		var zero T
		return zero, ErrTimeout
	}
}

// RecvCtx waits for one value or for the context to end. The caller picks
// the deadline (context.WithTimeout) and the error says why it ended:
// context.DeadlineExceeded or context.Canceled.
func RecvCtx[T any](ctx context.Context, ch <-chan T) (T, error) {
	select {
	case v := <-ch:
		return v, nil
	case <-ctx.Done():
		var zero T
		return zero, ctx.Err()
	}
}

// IdleLoop handles messages until the input closes (nil error), the
// context ends (ctx.Err()), or no message arrives for idle (ErrIdle).
// One Timer is created and Reset after every message instead of a new
// time.After per iteration.
func IdleLoop[T any](ctx context.Context, in <-chan T, idle time.Duration, handle func(T)) error {
	timer := time.NewTimer(idle)
	defer timer.Stop()
	for {
		select {
		case v, ok := <-in:
			if !ok {
				return nil
			}
			handle(v)
			// With go 1.23+ in go.mod, Reset discards any stale tick;
			// no Stop-and-drain dance is needed.
			timer.Reset(idle)
		case <-timer.C:
			return ErrIdle
		case <-ctx.Done():
			return ctx.Err()
		}
	}
}

// CollectFor gathers values for at most total. The deadline channel is
// created ONCE, before the loop, so it bounds the whole collection.
func CollectFor[T any](in <-chan T, total time.Duration) []T {
	var got []T
	deadline := time.After(total)
	for {
		select {
		case v, ok := <-in:
			if !ok {
				return got
			}
			got = append(got, v)
		case <-deadline:
			return got
		}
	}
}

// CollectForBuggy is the common mistake: time.After inside the loop makes
// a fresh timer on every iteration, so "total" silently becomes "idle".
// While values keep arriving faster than total, it never times out.
func CollectForBuggy[T any](in <-chan T, total time.Duration) []T {
	var got []T
	for {
		select {
		case v, ok := <-in:
			if !ok {
				return got
			}
			got = append(got, v)
		case <-time.After(total): // BUG: restarts every iteration
			return got
		}
	}
}

// StaleAfterReset reports whether a receive right after Reset returns at
// once, which would mean a stale tick from before Reset was delivered.
// The timer fires, nobody reads it, then it is Reset to a long duration.
func StaleAfterReset() bool {
	t := time.NewTimer(time.Millisecond)
	defer t.Stop()
	time.Sleep(20 * time.Millisecond) // the timer has fired; C is unread
	t.Reset(time.Hour)
	select {
	case <-t.C:
		return true // pre-1.23 semantics: buffered stale value
	default:
		return false // Go 1.23+ semantics: no stale value
	}
}

The Go angle ​

Go has no receive(timeout), no poll(), no waitAny(): everything is select, and the standard library adapts to it by handing out channels. time.After, time.Timer.C, time.Ticker.C, context.Context.Done(), http.Request.Context().Done() and os/signal.Notify all produce channels so they can sit next to your data channels in one statement. The flip side is that select only understands channels: a sync.Mutex, a sync.Cond, a sync.WaitGroup or a blocking syscall cannot be a case, which is why idiomatic Go turns those into channels when they must be waited on together (for example wg.Wait() in a goroutine that closes a done channel).

The concept catalogue ​

The select statement Must-know ​

In plain words: select lists several sends and receives. It runs exactly one of them, then that case's body, and then continues after the select.

Common misunderstanding: "Only the chosen case's expressions run." The specification says the channel operands of every receive and the channel and value of every send "are evaluated exactly once, in source order, upon entering the select statement", and "any side effects in that evaluation will occur irrespective of which (if any) communication operation is selected". A case out <- expensive(): computes expensive() even when another case wins.

Definition: The grammar allows three kinds of case: a send statement (case ch <- v:), a receive optionally assigned to one or two variables (case v := <-ch:, case v, ok := <-ch:, case a[f()] = <-ch:), and at most one default. Execution: (1) evaluate operands; (2) if one or more communications can proceed, choose one "via a uniform pseudo-random selection"; (3) otherwise run default if present; (4) otherwise block until one can proceed; (5) perform the communication, then evaluate the left side of an assignment, then run the statement list. There is no fallthrough between cases. break inside a case leaves the select.

1  enter select
2  evaluate: chan ready, chan blocked, value()        (source order, all cases)
3  ready set = {recv ready}                           (blocked has no receiver)
4  run: v := <-ready ; case body
5  value() was still called once (lab experiment 3)

Real scenarios: an HTTP handler waiting on a backend or the request context; a consumer reading two queues; a goroutine sending a result or giving up when cancelled; a server loop reading commands, ticks and shutdown.

1. Evaluate oncechannels + send values2. Any case ready?poll in random order3a. Pick one at randomuniform among ready4. Communicateassign recv, run case body3b. default present?yes: run default, no wait3c. Park goroutineenqueued on every channelstate: [select]Nil channels skippedall nil, no default:blocks foreveryesnono defaultone channel wakes it;dequeue from the restLocks are taken in channel-address order, so two selects on the same channels cannot deadlock each other
go
// Package basics shows the core semantics of the select statement:
// non-blocking operations with default, the uniform random choice among
// ready cases, nil channels that disable a case, and closed channels that
// are always ready.
package basics

// RecvState reports what a non-blocking receive observed.
type RecvState int

const (
	Empty    RecvState = iota // no value was ready; default ran
	Received                  // a value sent by someone was received
	Closed                    // the channel is closed and drained
)

func (s RecvState) String() string {
	switch s {
	case Empty:
		return "empty"
	case Received:
		return "received"
	case Closed:
		return "closed"
	}
	return "unknown"
}

// TryRecv is a non-blocking receive: it never waits.
func TryRecv[T any](ch <-chan T) (T, RecvState) {
	select {
	case v, ok := <-ch:
		if !ok {
			var zero T
			return zero, Closed
		}
		return v, Received
	default:
		var zero T
		return zero, Empty
	}
}

// TrySend is a non-blocking send: it reports false instead of waiting
// when no receiver is ready and the buffer (if any) is full.
// Like any send, it panics if ch is closed.
func TrySend[T any](ch chan<- T, v T) bool {
	select {
	case ch <- v:
		return true
	default:
		return false
	}
}

// CountChoices runs n selects whose two cases are both always ready
// (closed channels) and counts how often each case won.
func CountChoices(n int) (first, second int) {
	a := make(chan struct{})
	b := make(chan struct{})
	close(a)
	close(b)
	for range n {
		select {
		case <-a:
			first++
		case <-b:
			second++
		}
	}
	return first, second
}

// Merge2 forwards every value from a and b to the returned channel and
// closes it once both inputs are closed. A closed input is set to nil so
// its case can never be chosen again (a nil channel blocks forever).
func Merge2[T any](a, b <-chan T) <-chan T {
	out := make(chan T)
	go func() {
		defer close(out)
		for a != nil || b != nil {
			select {
			case v, ok := <-a:
				if !ok {
					a = nil
					continue
				}
				out <- v
			case v, ok := <-b:
				if !ok {
					b = nil
					continue
				}
				out <- v
			}
		}
	}()
	return out
}

// SpinsOnClosed shows the bug Merge2 avoids: it counts how many times a
// select chooses a closed channel case within max iterations when the
// closed channel is NOT set to nil. The answer is every time.
func SpinsOnClosed(max int) int {
	done := make(chan struct{})
	close(done)
	never := make(chan int)
	spins := 0
	for range max {
		select {
		case _, ok := <-done:
			if !ok {
				spins++ // a real loop that forgets to nil the channel spins here
			}
		case <-never:
		}
	}
	return spins
}

// EvaluationOrder demonstrates that every channel operand and every value
// to send is evaluated once on entry, even for the case that is not
// chosen. It returns the trace of evaluations and the chosen case.
func EvaluationOrder() (trace []string, chosen string) {
	ready := make(chan int, 1)
	ready <- 7
	blocked := make(chan int) // nobody receives
	pick := func(name string, ch chan int) chan int {
		trace = append(trace, "chan "+name)
		return ch
	}
	value := func() int {
		trace = append(trace, "value")
		return 42
	}
	select {
	case v := <-pick("ready", ready):
		_ = v
		chosen = "recv ready"
	case pick("blocked", blocked) <- value():
		chosen = "send blocked"
	}
	return trace, chosen
}

Random selection among ready cases Must-know ​

In plain words: If more than one case can run, Go picks one at random, with equal chances. Writing a case first does not make it more likely.

Common misunderstanding: "The runtime is free to pick any order, so it probably takes the first." It is required to be uniform. Lab experiment 1 counts 100 000 selects on two always-ready channels: 50 029 versus 49 971 on the machine that wrote this page.

Definition: "a single one that can proceed is chosen via a uniform pseudo-random selection" (specification). The runtime builds a random permutation of the non-nil cases (pollorder, filled with cheaprandn in runtime/select.go) and takes the first ready case in that order. The randomness is per execution of the statement, not per program.

           iteration 1     iteration 2     iteration 3
a ready    yes             yes             yes
b ready    yes             yes             yes
pollorder  [b a]           [a b]           [a b]
runs       b               a               a        -> about 50/50 over many runs

Real scenarios: two queues with equal importance; a select over a data channel and ctx.Done() when both are ready at once (the job case may still win: see StopFirst); tests that accidentally depend on order and fail one run in two.

SituationOutcome
One case readyThat case runs
Several readyUniform random choice among them
None ready, default presentdefault runs
None ready, no defaultGoroutine parks until one is ready
All channels nil, no defaultBlocks forever

Non-blocking send and receive Must-know ​

In plain words: Add default: and the select never waits: if the send or receive cannot happen immediately, default runs instead.

Common misunderstanding: "A non-blocking send is safe on a closed channel." A send to a closed channel is ready (it can proceed) and proceeds by panicking: panic: send on closed channel. default protects against "would wait", not against "is closed". The TrySend test asserts that panic.

Definition: A non-blocking receive select { case v, ok := <-c: ...; default: ... } has three outcomes: a value (ok == true), closed (ok == false, zero value) or empty (default). A non-blocking send select { case c <- v: ...; default: ... } has two: delivered (a receiver was waiting or the buffer had room) or not. The compiler rewrites a select with one case plus default into a single cheap runtime call (runtime/select.go: "The compiler rewrites selects that statically have only 0 or 1 cases plus default into simpler constructs"), which is why the benchmark below measures it at under 3 ns.

1  ch := make(chan int, 1)
2  TryRecv(ch)        -> empty     (default ran)
3  ch <- 9
4  TryRecv(ch)        -> received 9
5  close(ch)
6  TryRecv(ch)        -> closed    (ok == false)
7  TryRecv(nilChan)   -> empty     (a nil channel is never ready)

Real scenarios: Effective Go's leaky-buffer free list ("Grab a buffer if available; allocate if not" and "Free list full, just carry on"); the 2010 blog's Query that sends the first replica's answer and lets the others drop theirs; dropping metrics when an exporter is slow; checking whether a timer fired without waiting (the Go 1.23 notes recommend this over len(t.C)).

Nil channel cases Must-know ​

In plain words: A case on a nil channel is switched off. Set a channel variable to nil and its case can never be chosen until you assign a real channel again.

Common misunderstanding: "A nil channel is an error." Sending to or receiving from a nil channel blocks forever (specification: "Receiving from a nil channel blocks forever", "A send on a nil channel blocks forever"); only close(nil) panics. In a select that blocking turns into "never ready", which Ajmani's 2013 talk lists as a feature: "Sends and receives on nil channels block. Select never selects a blocking case."

Definition: The runtime omits cases whose channel is nil from the poll and lock orders ("Omit cases without channels from the poll and lock orders"). A select whose cases are all nil and has no default blocks forever; in main with nothing else running that is the deadlock in Error texts with goroutine state [select].

1  for a != nil || b != nil {
2    select { case v, ok := <-a: ... ; case v, ok := <-b: ... }
3  }
4  a closes        -> ok == false -> a = nil   (case a off)
5  b keeps sending -> only case b can run
6  b closes        -> b = nil -> loop condition false -> close(out)

Real scenarios: merging inputs that finish at different times (Merge2); a send case that should exist only when there is something pending (the Poller sets updates to nil while its queue is empty, from Ajmani's talk); pausing intake while a buffer is full; turning off a timer case after it fired.

input aclosed: a = nilinput bstill openmerge goroutinefor a != nil || b != nilselect { case <-a; case <-b }nil case never chosenoutclosed at the enddisabledWithout a = nila closed channel is always ready: the loop spins on zero values

Closed channel cases Must-know ​

In plain words: A receive from a closed channel never waits. In a select, that case is ready every single time.

Common misunderstanding: "After I've seen the close once, the case goes quiet." It does not. Lab experiment 4: in 1000 iterations of a select over a closed channel and a channel that never delivers, the closed case won 1000 times. A merge loop that handles ok == false with continue but does not set the variable to nil becomes a busy loop.

Definition: "A receive operation on a closed channel can always proceed immediately, yielding the element type's zero value after any previously sent values have been received." Values already buffered are delivered first; only then does the receive start returning ok == false. Closing is "synchronized before a receive that returns a zero value because the channel is closed" (Go Memory Model), which is what makes close(done) safe as a signal for writes made before it.

1  ch has buffered 1, 2 ; close(ch)
2  <-ch -> 1, ok=true
3  <-ch -> 2, ok=true
4  <-ch -> 0, ok=false     (and every receive after this)

Real scenarios: ctx.Done() (a channel closed on cancellation, so every goroutine watching it wakes); a done channel closed with defer close(done) in a pipeline; a shutdown broadcast to N workers; the bug where a loop over a closed input burns a core.

PatternCorrect handling of ok == false
Merge loopset the variable to nil
Worker reading jobsreturn (producer finished)
Done/quit channelreturn; the close is the message
Optional inputkeep the case but stop reading: nil

Timeouts with time.After Must-know ​

In plain words: time.After(d) returns a channel that receives one value after d. Put it as a case and the select gives up after d.

Common misunderstanding: "time.After leaks and must never be used." That was true for unfired timers before Go 1.23. The current go doc time.After says: "As of Go 1.23, the garbage collector can recover unreferenced, unstopped timers. There is no reason to prefer NewTimer when After will do." The real remaining trap is semantic, not memory: in a loop it creates a fresh timer every iteration (next section).

Definition: time.After(d) "is equivalent to NewTimer(d).C". The timer starts when time.After is evaluated, which is on entry to the select (operands are evaluated first). The 2010 blog built the same thing by hand with a goroutine that sleeps and sends on a buffered channel and noted: "In real programs you should use time.After".

1  select {
2  case v := <-ch:              // value within 1 s
3  case <-time.After(time.Second):  // timer started at line 1
4  }
5  t=0      enter, timer starts
6  t=1.0s   timer channel ready -> timeout case runs

Real scenarios: one RPC reply with a limit; waiting for a lock-free handoff in a test; a CLI that waits a few seconds for a background flush on exit.

Timers in loops: the time.After trap, NewTimer, Stop and Reset Must-know ​

In plain words: A time.After inside a for-select is a new timer each time round the loop. If you meant "give up after 30 seconds in total", you wrote "give up after 30 seconds of silence". Create the timer once, outside the loop, or create one time.NewTimer and Reset it.

Common misunderstanding: "The timer leak is the problem." On modules at go 1.23 or later (and on every module built with Go 1.27, which removed the old mode) unreferenced timers are collected. Two problems remain: the wrong meaning (idle instead of total), which Pike's 2012 talk shows as "Create the timer once, outside the loop, to time out the entire conversation", and the allocation of one timer per iteration in a hot loop. On older modules built with toolchains before 1.27, there is also the old leak: "Earlier versions of Go did not collect unstopped Timers until after they had fired".

Definition:

CallMeaning (Go 1.23+ semantics)
t := time.NewTimer(d)one timer, channel t.C
t.Stop()true if it stopped a running timer; afterwards a receive from t.C "is guaranteed to block rather than receive a stale time value"
t.Reset(d)re-arm; a receive after Reset "is guaranteed not to receive a time value corresponding to the previous timer settings"
before Go 1.23"the only safe way to use Reset was to call Timer.Stop and explicitly drain the timer first"
len(t.C), cap(t.C)now 0; poll with a non-blocking receive instead
GODEBUG=asynctimerchan=1old buffered behaviour on 1.23 to 1.26; removed in 1.27

The gate: "These new behaviors are only enabled when the main Go program is in a module with a go.mod go line using Go 1.23.0 or later." Go 1.27 then says: "The asynctimerchan GODEBUG setting (added in Go 1.23) has been removed permanently. Channels created by package time are now always unbuffered (synchronous), irrespective of GODEBUG settings."

producer sends every 2 ms for 100 ms; limit 30 ms
CollectFor       deadline := time.After(30ms) before the loop -> 12 values, returns at 30 ms
CollectForBuggy  case <-time.After(30ms) inside the loop      -> 50 values, returns at 130 ms
                 (every message restarts the 30 ms timer; it fires only after the producer stops)

Real scenarios: an idle timeout on a connection reset by every message (IdleLoop, one Timer, Reset after each message); "collect for up to 1 s then flush a batch" (CollectFor); a debouncer; a lease that must expire at a fixed time regardless of traffic.

go
package timeouts

import (
	"context"
	"errors"
	"testing"
	"time"
)

func TestRecvTimeout(t *testing.T) {
	ch := make(chan int, 1)
	if _, err := RecvTimeout(ch, 10*time.Millisecond); !errors.Is(err, ErrTimeout) {
		t.Fatalf("want ErrTimeout, got %v", err)
	}
	ch <- 3
	if v, err := RecvTimeout(ch, time.Second); err != nil || v != 3 {
		t.Fatalf("got %v %v", v, err)
	}
}

func TestRecvCtxDeadline(t *testing.T) {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond)
	defer cancel()
	_, err := RecvCtx(ctx, make(chan int))
	if !errors.Is(err, context.DeadlineExceeded) {
		t.Fatalf("want DeadlineExceeded, got %v", err)
	}
	if err.Error() != "context deadline exceeded" {
		t.Fatalf("text %q", err.Error())
	}
}

func TestRecvCtxCanceled(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	cancel()
	_, err := RecvCtx(ctx, make(chan int))
	if !errors.Is(err, context.Canceled) || err.Error() != "context canceled" {
		t.Fatalf("got %v", err)
	}
}

func TestIdleLoop(t *testing.T) {
	in := make(chan int)
	go func() {
		for i := range 5 {
			in <- i
			time.Sleep(5 * time.Millisecond) // well under the idle limit
		}
		// then silence: the loop must give up after idle
	}()
	n := 0
	err := IdleLoop(context.Background(), in, 60*time.Millisecond, func(int) { n++ })
	if !errors.Is(err, ErrIdle) || n != 5 {
		t.Fatalf("err=%v n=%d", err, n)
	}
}

func TestIdleLoopInputClosed(t *testing.T) {
	in := make(chan int)
	close(in)
	if err := IdleLoop(context.Background(), in, time.Second, func(int) {}); err != nil {
		t.Fatalf("closed input should end with nil, got %v", err)
	}
}

// producer sends a value every 2 ms for about 150 ms, then closes.
func producer() <-chan int {
	out := make(chan int)
	go func() {
		defer close(out)
		stop := time.After(150 * time.Millisecond)
		for i := 0; ; i++ {
			select {
			case out <- i:
			case <-stop:
				return
			}
			time.Sleep(2 * time.Millisecond)
		}
	}()
	return out
}

func TestOverallDeadlineVersusPerIterationAfter(t *testing.T) {
	start := time.Now()
	good := CollectFor(producer(), 30*time.Millisecond)
	goodTook := time.Since(start)

	start = time.Now()
	bad := CollectForBuggy(producer(), 30*time.Millisecond)
	badTook := time.Since(start)

	if goodTook > 100*time.Millisecond {
		t.Fatalf("overall deadline ignored: took %v", goodTook)
	}
	if badTook < 120*time.Millisecond {
		t.Fatalf("buggy version should run until the producer stops, took %v", badTook)
	}
	if len(bad) <= len(good) {
		t.Fatalf("buggy collected %d, good %d", len(bad), len(good))
	}
	t.Logf("CollectFor: %d values in %v; CollectForBuggy: %d values in %v",
		len(good), goodTook.Round(time.Millisecond), len(bad), badTook.Round(time.Millisecond))
}

func TestNoStaleValueAfterReset(t *testing.T) {
	// go.mod says go 1.24, so timer channels are synchronous.
	if StaleAfterReset() {
		t.Fatal("stale tick delivered after Reset")
	}
}

Cancellation with ctx.Done Must-know ​

In plain words: Every blocking step in a goroutine that might need to stop gets a second case, case <-ctx.Done():, and returns ctx.Err().

Common misunderstanding: "Cancelling the context stops the goroutine." Nothing stops a goroutine from outside. cancel() closes the Done channel; the goroutine stops only if it is in (or reaches) a select with that case, or checks ctx.Err(). A goroutine blocked on a plain out <- v ignores the context and leaks. The Code Review Comments wiki: "Goroutines can leak by blocking on channel sends or receives: the garbage collector will not terminate a goroutine even if the channels it is blocked on are unreachable."

Definition: ctx.Done() returns a channel that is closed when the context is cancelled or its deadline passes; ctx.Err() then returns context.Canceled ("context canceled") or context.DeadlineExceeded ("context deadline exceeded"). context.WithTimeout(parent, d) returns a child and a cancel function that must be called (go vet: "the cancel function returned by context.WithTimeout should be called, not discarded, to avoid a context leak"). Creation and propagation of contexts are covered in context.

   main                         worker
1  ctx, cancel := WithCancel    select { case out <- v: ; case <-ctx.Done(): }
2                                (blocked: nobody reads out)
3  cancel()  -> close(Done)
4                                Done ready -> return ctx.Err()  // context canceled
5  without the Done case: worker blocked forever, goroutine leak

Real scenarios: HTTP handlers (r.Context() ends when the client disconnects); background jobs on SIGTERM via signal.NotifyContext (OS Processes, Signals & Graceful Shutdown); a pipeline where a downstream error must stop upstream stages; database calls that take a context in database/sql.

Blocking stepWithout a ctx.Done() caseWith it
out <- vleaks if reader leftreturns ctx.Err()
v := <-inwaits forever if producer diedreturns ctx.Err()
time.Sleep(d)cannot be interrupteduse a timer case instead
wg.Wait()cannot be a casewrap: goroutine closes done after Wait
mu.Lock()cannot be a caseredesign with a channel semaphore

The for-select loop Must-know ​

In plain words: A goroutine that owns some state runs for { select { ... } } forever: each case reacts to one kind of event, and the loop goes back to waiting.

Common misunderstanding: "break exits the loop." Inside a select, break exits the select only. Use return, a labelled break loop, or a loop condition. The second mistake is a loop with no exit at all: every for-select needs at least one case that returns (closed input, ctx.Done(), quit request).

Definition: Ajmani's 2013 structure: "loop runs in its own goroutine. select lets loop avoid blocking indefinitely in any one state. ... The cases interact via local state in loop." The state is owned by the loop goroutine, so it needs no mutex. The exits are explicit:

ExitCaseReturn value
Input finishedcase j, ok := <-jobs: with !oknil
Cancellationcase <-ctx.Done():ctx.Err()
Owner asks to stopcase errc := <-closing:reply on errc, then return
Idlecase <-idle.C:ErrIdle
Fatal error in a casereturn err from the case bodythe error
      for {
1       select {
2       case <-ctx.Done():   drain(); return ctx.Err()
3       case j, ok := <-jobs: if !ok { return nil }; process(j)
4       case <-tk.C:          beat()
5       }
6     }                       back to 1 after cases 3 and 4

Real scenarios: a job consumer; a WebSocket connection's writer loop (messages, pings, close); an in-memory cache with an expiry ticker; the event loop of a game server; a poller that fetches every N seconds.

for { select { ... } }parked until a case is readycase <-ctx.Done()drain buffered jobs(non-blocking)case j, ok := <-jobsok: Process(j)!ok: channel closedcase <-ticker.Cheartbeat, metricsTicker.Reset(d) to retunereturn ctx.Err()context canceledreturn nilproducer finished!okloop againEvery exit is a return in a case:a plain break only leavesthe select, not the for
go
// Package forselect shows for-select loops: a worker with jobs, a
// heartbeat ticker and graceful shutdown; a ticker whose period changes
// at run time; the quit-channel service from "Advanced Go Concurrency
// Patterns"; and the busy loop that a default case creates.
package forselect

import (
	"context"
	"time"
)

// Job is a unit of work.
type Job struct{ ID int }

// Worker processes jobs until the context ends or the jobs channel closes.
type Worker struct {
	Jobs      <-chan Job
	Heartbeat time.Duration
	Process   func(Job)
	OnBeat    func()
	// Drain, when true, processes jobs that are already buffered after
	// cancellation instead of abandoning them.
	Drain bool
}

// Run is the for-select loop. It has exactly three ways out: the jobs
// channel is closed (nil error), the context ends (ctx.Err()), or a
// panic in Process.
func (w *Worker) Run(ctx context.Context) error {
	tk := time.NewTicker(w.Heartbeat)
	defer tk.Stop()
	for {
		select {
		case <-ctx.Done():
			if w.Drain {
				w.drain()
			}
			return ctx.Err()
		case j, ok := <-w.Jobs:
			if !ok {
				return nil
			}
			w.Process(j)
		case <-tk.C:
			if w.OnBeat != nil {
				w.OnBeat()
			}
		}
	}
}

// drain takes whatever is buffered right now without waiting for more.
func (w *Worker) drain() {
	for {
		select {
		case j, ok := <-w.Jobs:
			if !ok {
				return
			}
			w.Process(j)
		default:
			return
		}
	}
}

// Beats sends a tick count on out every period until ctx ends; a value
// received on setPeriod changes the period with Ticker.Reset.
func Beats(ctx context.Context, period time.Duration, setPeriod <-chan time.Duration, out chan<- int) {
	tk := time.NewTicker(period)
	defer tk.Stop()
	n := 0
	for {
		select {
		case <-ctx.Done():
			return
		case d := <-setPeriod:
			tk.Reset(d) // next tick arrives d after this call
		case <-tk.C:
			n++
			select { // never let a slow reader block the heartbeat
			case out <- n:
			default:
			}
		}
	}
}

The busy loop Important ​

In plain words: for { select { case <-c: ...; default: } } never waits. When nothing is ready it loops again immediately, burning a CPU core.

Common misunderstanding: "default with time.Sleep(time.Millisecond) fixes it." It trades CPU for latency and still wakes 1000 times a second. If the goroutine has nothing to do until a channel is ready, remove default and let select block; the scheduler parks the goroutine at no CPU cost.

Definition: default is for "do something else useful if nothing is ready" (one try, inside a larger step), not for waiting. Lab experiment 7: the busy version ran about two million iterations in 10 ms; BlockingWait woke exactly once.

busy:      select -> default -> select -> default -> ... (millions per second, 100 % CPU)
blocking:  select -> park ............................ stop closed -> wake once

Real scenarios: a consumer that polls a channel with default and shows up as 100 % CPU in top while idle; a test that "waits" for a flag with a spin loop and slows the race detector to a crawl; a game loop that should be driven by a Ticker.

go
package forselect

import "time"

// BusyPoll is the anti-pattern: a for-select with default never blocks,
// so the loop spins on a CPU core while it waits. It returns how many
// iterations ran before stop was closed.
func BusyPoll(stop <-chan struct{}) int {
	spins := 0
	for {
		select {
		case <-stop:
			return spins
		default:
			spins++ // "nothing to do", over and over
		}
	}
}

// BlockingWait is the fix: without default the goroutine parks until a
// case is ready and uses no CPU meanwhile. It returns 1 (one wake-up).
func BlockingWait(stop <-chan struct{}) int {
	wakeups := 0
	for {
		select {
		case <-stop:
			wakeups++
			return wakeups
		}
	}
}

// StopAfter closes the returned channel after d.
func StopAfter(d time.Duration) <-chan struct{} {
	c := make(chan struct{})
	time.AfterFunc(d, func() { close(c) })
	return c
}

Heartbeats and tickers Important ​

In plain words: A time.Ticker is a channel that ticks every period. As one case of a for-select it gives a loop a regular pulse: heartbeats, metric flushes, lease renewals, polling.

Common misunderstanding: "Ticks queue up while I'm busy." They do not: the ticker "will adjust the time interval or drop ticks to make up for slow receivers". A loop that takes 3 s per job with a 1 s ticker sees one tick after each job, not three. Second misunderstanding: "Stop is only for garbage collection." Since Go 1.23 unreferenced tickers are collectable, but "Code may of course still want to call Stop to stop the ticker for other reasons", for example a ticker still referenced by a long-lived struct.

Definition: time.NewTicker(d) panics if d <= 0 (non-positive interval for NewTicker). Ticker.Reset(d) (Go 1.15) "stops a ticker and resets its period to the specified duration. The next tick will arrive after the new period elapses." A heartbeat that is sent to another goroutine should itself be a non-blocking send so a slow monitor cannot stall the loop (Beats in the snippet).

1  tk := time.NewTicker(time.Hour)
2  set <- 5 * time.Millisecond        // case d := <-setPeriod: tk.Reset(d)
3  t=5ms  tick 1 ; t=10ms tick 2 ; t=15ms tick 3 ...
4  heartbeat send: select { case out <- n: ; default: }   // drop if monitor is slow

Real scenarios: liveness heartbeats to a supervisor; flushing batched writes every second; renewing a distributed lock lease at one third of its TTL; adaptive polling that slows down when idle (Ticker.Reset to a longer period) and speeds up under load.

Priority select Important ​

In plain words: select has no priorities. To prefer channel A, first try A without waiting, and only if it is empty, wait on A and B together.

Common misunderstanding: "Put the important case first." Order is irrelevant (Random selection). The plain-select test in the snippet lets the low-priority channel win about half the time with both ready. A second misunderstanding: "The two-step version gives strict priority." In the blocking second step, if both become ready during the same wake-up, the choice is random again; the guarantee is "high wins whenever it is already ready when we look".

Definition: Two shapes. (1) Nested/two-step: select { case v := <-high: return v; default: } then select { case v := <-high: ...; case v := <-low: ...; case <-ctx.Done(): ... }. (2) Cancellation first: check ctx.Err() before the select, so a cancelled worker never starts one more job merely because the job case won the coin toss (StopFirst).

high: [100 101 102]   low: [0 1 2]
Next x6 -> 100 101 102 0 1 2        (lab experiment 8)
NextPlain x6 -> e.g. 0 100 1 101 102 2   (random interleaving)

Real scenarios: control messages (config reload, shutdown) ahead of data; paid-tier jobs ahead of free-tier; retries behind fresh work; acknowledgements ahead of new sends in a protocol loop.

go
// Package priority shows how to prefer one channel over another. A
// single select picks uniformly at random among ready cases, so
// priority needs two steps: a non-blocking check of the preferred
// channel, then a blocking select over everything.
package priority

import "context"

// Next returns the next value, preferring high over low whenever both
// have a value ready. fromHigh reports which channel it came from.
func Next[T any](ctx context.Context, high, low <-chan T) (v T, fromHigh bool, err error) {
	// Step 1: the preferred channel, without waiting.
	select {
	case v = <-high:
		return v, true, nil
	default:
	}
	// Step 2: wait for anything. If both become ready at the same time
	// here, the choice is random again; that window is one wake-up wide.
	select {
	case v = <-high:
		return v, true, nil
	case v = <-low:
		return v, false, nil
	case <-ctx.Done():
		return v, false, ctx.Err()
	}
}

// NextPlain is the naive version: one select, no priority.
func NextPlain[T any](high, low <-chan T) (v T, fromHigh bool) {
	select {
	case v = <-high:
		return v, true
	case v = <-low:
		return v, false
	}
}

// StopFirst checks cancellation before taking new work, so a cancelled
// worker never starts one more job just because the job case won the
// random choice.
func StopFirst[T any](ctx context.Context, jobs <-chan T) (T, error) {
	var zero T
	if err := ctx.Err(); err != nil {
		return zero, err
	}
	select {
	case <-ctx.Done():
		return zero, ctx.Err()
	case j := <-jobs:
		return j, nil
	}
}

Quit channels versus context Important ​

In plain words: Before context (Go 1.7) every loop had its own quit channel: close it, or send on it, to stop the loop. Today ctx.Done() is the standard quit channel, and an explicit request channel is used when the owner also needs an answer back.

Common misunderstanding: "Context replaced quit channels completely." Context is one-way: it says stop, it cannot return the loop's final error or confirm that the loop has finished. Ajmani's closing chan chan error does both: "Close asks loop to exit and waits for a response." The loop replies on the channel it received, then returns.

Definition:

MechanismDirectionWaits for the loop to finishCarries an error backCrosses API boundaries
close(quit)one-way broadcastnonoawkward
quit <- true (Pike 2012)one-way, one receiveronly if unbufferednoawkward
ctx.Done()one-way broadcast, tree-shapednoctx.Err() onlyyes, the convention
closing chan chan errorrequest and replyyesyesinside one type
ctx plus WaitGroup or errgroupbroadcast plus joinyesyes (errgroup)yes
   caller                          loop goroutine
1  errc := make(chan error)
2  p.closing <- errc   ----------> case errc := <-p.closing:
3                                    errc <- lastErr ; close(p.Updates) ; return
4  err := <-errc  <---------------

Real scenarios: a Close() error on a subscription or poller type; a connection object whose Close must flush before returning; a library that must work without a context in its API.

go
package forselect

import (
	"errors"
	"time"
)

// Poller runs a loop in its own goroutine. Close asks the loop to exit
// and waits for its answer: the "closing chan chan error" shape.
type Poller struct {
	closing chan chan error
	Updates chan int
}

// ErrFetch is reported by Close when the last fetch failed.
var ErrFetch = errors.New("fetch failed")

// NewPoller starts the loop. fetch is called every interval; a failed
// fetch is remembered and returned by Close.
func NewPoller(interval time.Duration, fetch func() (int, error)) *Poller {
	p := &Poller{closing: make(chan chan error), Updates: make(chan int)}
	go p.loop(interval, fetch)
	return p
}

func (p *Poller) loop(interval time.Duration, fetch func() (int, error)) {
	var (
		pending []int
		lastErr error
	)
	tk := time.NewTicker(interval)
	defer tk.Stop()
	for {
		// A nil channel disables the send case while nothing is pending.
		var updates chan int
		var first int
		if len(pending) > 0 {
			updates = p.Updates
			first = pending[0]
		}
		select {
		case <-tk.C:
			v, err := fetch()
			if err != nil {
				lastErr = err
				continue
			}
			pending = append(pending, v)
		case updates <- first:
			pending = pending[1:]
		case errc := <-p.closing:
			errc <- lastErr
			close(p.Updates)
			return
		}
	}
}

// Close stops the loop and returns the last fetch error, if any.
func (p *Poller) Close() error {
	errc := make(chan error)
	p.closing <- errc
	return <-errc
}

Fan-in with select Must-know ​

In plain words: Fan-in merges several channels into one. With a fixed small number of inputs, one goroutine selects over all of them; with any number, one goroutine per input forwards into a shared output and a WaitGroup closes the output at the end.

Common misunderstanding: "A forwarder is just for v := range in { out <- v }." That send blocks forever if the consumer of out stops reading. Each forwarder's send needs a ctx.Done() case. Also, the output must be closed exactly once, after all forwarders finish; closing it from a forwarder panics the others (send on closed channel).

Definition: Static fan-in: select over a known set, nil-ing closed inputs (Merge2). Per-input fan-in: one goroutine per input plus wg.Wait(); close(out) (Merge, the shape from the pipelines blog). Dynamic fan-in in one goroutine: reflect.Select (below). Since Go 1.22 the loop variable is per iteration, so go func() { ... in ... }() inside for _, in := range inputs captures the right channel without the old in := in line. Fan-out (distributing work) and bounded worker pools are in Worker Pools, Pipelines, Fan-Out/Fan-In.

in1 ──┐ forwarder 1: select { out <- v ; <-ctx.Done() }
in2 ──┼ forwarder 2              ──▶ out ──▶ consumer
in3 ──┘ forwarder 3
wg.Wait() -> close(out)          (only after all forwarders return)

Real scenarios: merging results from several replicas or shards; collecting logs from many connections; combining a user-event stream and a system-event stream into one handler; scatter-gather where the first N answers are enough.

go
// Package fanin merges many input channels into one: with a goroutine
// per input (static fan-in) and with reflect.Select in one goroutine
// when the set of channels is only known at run time.
package fanin

import (
	"context"
	"reflect"
	"sync"
)

// Merge starts one forwarding goroutine per input. Each forwarder uses
// select so it also stops when ctx ends, instead of blocking forever on
// a send nobody will receive.
func Merge[T any](ctx context.Context, inputs ...<-chan T) <-chan T {
	out := make(chan T)
	var wg sync.WaitGroup
	for _, in := range inputs {
		wg.Add(1)
		go func() {
			defer wg.Done()
			for v := range in {
				select {
				case out <- v:
				case <-ctx.Done():
					return
				}
			}
		}()
	}
	go func() {
		wg.Wait()
		close(out)
	}()
	return out
}

// MergeReflect uses a single goroutine and reflect.Select over a case
// list built at run time. Case 0 is ctx.Done; closed inputs are removed.
func MergeReflect[T any](ctx context.Context, inputs ...<-chan T) <-chan T {
	out := make(chan T)
	cases := make([]reflect.SelectCase, 0, len(inputs)+1)
	cases = append(cases, reflect.SelectCase{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(ctx.Done())})
	for _, in := range inputs {
		cases = append(cases, reflect.SelectCase{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(in)})
	}
	go func() {
		defer close(out)
		for len(cases) > 1 {
			chosen, v, ok := reflect.Select(cases)
			if chosen == 0 {
				return // ctx done
			}
			if !ok {
				cases = append(cases[:chosen], cases[chosen+1:]...) // input closed
				continue
			}
			select {
			case out <- v.Interface().(T):
			case <-ctx.Done():
				return
			}
		}
	}()
	return out
}

Bounded send: drop, wait, or backpressure Must-know ​

In plain words: A buffered channel is a bounded queue. When it is full, the producer must decide: drop the item, wait a little and then fail, or wait as long as it takes (slowing the producer down to the consumer's speed).

Common misunderstanding: "A bigger buffer solves it." A buffer only absorbs bursts; if the consumer is slower on average, any buffer fills and the decision returns. The decision is a product decision: losing a metric sample is fine, losing an order is not.

Definition:

PolicyCodeWhen fullUse for
Drop on fullselect { case ch <- v: ; default: dropped++ }returns at once, item lost, countedmetrics, logs, best-effort notifications, Effective Go's free list
Wait with timeoutnon-blocking try, then select { case ch <- v: ; case <-t.C: return ErrFull }waits up to d, then errorrequest handling: fail fast with 503
Backpressureselect { case ch <- v: ; case <-ctx.Done(): return ctx.Err() }waits until room or cancelledjobs that must not be lost; pipelines
Drop oldestreceive one non-blocking, then sendevicts the headlatest-value-wins: positions, prices
queue size 3, producer offers 0..9 with Offer
kept = 3 (0 1 2), dropped = 7                   (lab experiment 9)
OfferTimeout(v, 15ms) on a full queue -> ErrFull after 15 ms
Put(ctx, v) on a full queue, ctx 20 ms -> context deadline exceeded

Real scenarios: an audit log writer that must never block a request (drop and alert); an ingest endpoint that returns 503 when its queue is full (Load Shedding); a pipeline stage that slows its producer (Backpressure & Flow Control); a GPS stream where only the latest position matters.

ch <- vbuffer has room?sentno waitingDrop: defaultnever blocks; count dropsmetrics, logs, best effortWait up to d: timerthen ErrFull to callerAPI requests, 503 on fullWait: ctx.Donebackpressure to producermust not lose: orders, jobsyesfull: pick a policyA plain send on a full channel with no select blocks forever if the consumer died
go
// Package bounded is a buffered channel used as a bounded queue with the
// three producer policies: drop when full, wait up to a timeout, or wait
// until the context ends.
package bounded

import (
	"context"
	"errors"
	"sync/atomic"
	"time"
)

// ErrFull is returned when the queue stayed full for the whole wait.
var ErrFull = errors.New("queue full")

// Queue wraps a buffered channel; C is the consumer side.
type Queue[T any] struct {
	ch      chan T
	dropped atomic.Int64
}

// New makes a queue holding at most size items.
func New[T any](size int) *Queue[T] { return &Queue[T]{ch: make(chan T, size)} }

// C is the receive side for consumers.
func (q *Queue[T]) C() <-chan T { return q.ch }

// Dropped counts items rejected by Offer.
func (q *Queue[T]) Dropped() int64 { return q.dropped.Load() }

// Offer never blocks: it drops the item when the buffer is full
// (load shedding; good for metrics, logs, best-effort events).
func (q *Queue[T]) Offer(v T) bool {
	select {
	case q.ch <- v:
		return true
	default:
		q.dropped.Add(1)
		return false
	}
}

// OfferTimeout waits at most d for room, then gives up with ErrFull.
func (q *Queue[T]) OfferTimeout(v T, d time.Duration) error {
	select {
	case q.ch <- v:
		return nil
	default: // fast path: no timer when there is room
	}
	t := time.NewTimer(d)
	defer t.Stop()
	select {
	case q.ch <- v:
		return nil
	case <-t.C:
		return ErrFull
	}
}

// Put blocks until there is room or ctx ends (backpressure: the
// producer slows down to the consumer's pace).
func (q *Queue[T]) Put(ctx context.Context, v T) error {
	select {
	case q.ch <- v:
		return nil
	case <-ctx.Done():
		return ctx.Err()
	}
}

Blocking forever: select {} Good to know ​

In plain words: select {} has no cases, so it can never proceed: the goroutine parks forever.

Common misunderstanding: "It is a busy wait." It is a park with no CPU use (gopark with reason select (no cases) in runtime/select.go). The other misunderstanding: "It is a clean way to keep a server running." Only if something else is running and the program has another way to exit; otherwise the runtime detects that every goroutine is blocked and aborts with fatal error: all goroutines are asleep - deadlock!, goroutine state [select (no cases)].

Definition: The specification lists it as an example: select {} // block forever. Prefer waiting on something meaningful (a signal context, srv.ListenAndServe returning, an errgroup.Wait) so shutdown has a path.

1  go serve()        // runs forever, so no deadlock report
2  select {}         // main parks
3  SIGTERM           // default action kills the process: no defers, no drain

Real scenarios: tiny demo servers; plugins whose host keeps the process alive; WebAssembly main functions that must not return while callbacks are registered.

reflect.Select for dynamic cases Good to know ​

In plain words: When the number of channels is only known at run time, build a slice of reflect.SelectCase and call reflect.Select(cases).

Common misunderstanding: "It is the normal way to merge many channels." It is slower (lab benchmark: about 54 ns and one allocation for two cases, against about 35 ns and none for a compiled select), loses static typing (values come back as reflect.Value) and is capped: "Select supports a maximum of 65536 cases." A goroutine per input is usually simpler.

Definition: func Select(cases []SelectCase) (chosen int, recv Value, recvOK bool): "Like the Go select statement, it blocks until at least one of the cases can proceed, makes a uniform pseudo-random choice, and then executes that case." SelectCase{Dir, Chan, Send} with Dir one of SelectSend, SelectRecv, SelectDefault; a zero Chan makes the case ignored (the reflect version of a nil channel). recvOK == false means the channel is closed. Removing a closed case from the slice is the reflect version of ch = nil.

cases = [ctx.Done, in0, in1, ..., in99]
chosen, v, ok := reflect.Select(cases)
chosen == 0          -> ctx done, return
ok == false          -> remove cases[chosen]
else                 -> forward v.Interface().(T)

Real scenarios: a multiplexer over a configurable set of subscriptions; a test harness that waits on any of N channels; a plugin bus where channels are registered at run time. See reflect: When and How for the cost model of reflection.

Fairness and starvation Important ​

In plain words: Within one select, ready cases get equal chances. Across a whole system, a channel can still starve: if one case is always ready and does slow work, others wait their turn behind it.

Common misunderstanding: "Random choice guarantees fair throughput." It guarantees a fair coin per execution. If fast has 1000 items and slow has 1, the slow one gets on average one turn per two iterations while it is ready, which is fine; but if the loop body for one case takes 100 ms, every other case waits 100 ms. And random choice is the reason a cancellation can lose to a job several times in a row (probability halves each time, never zero).

Definition: Fairness is per statement and statistical. Starvation sources: long case bodies (move work out of the loop goroutine), a case that is always ready (closed channel not nil-ed, a hot channel), more producers than one consumer can serve, and priority code that never yields to the low channel. Ajmani's 2013 talk moved the slow Fetch out of the loop into a goroutine so the loop stays responsive.

iteration   ready set            chosen   time in body
1           {jobs, done}          jobs     100 ms
2           {jobs, done}          jobs     100 ms    (1/4 chance of this sequence)
3           {jobs, done}          done     return    -> shutdown delayed by 200 ms
fix: ctx.Err() check before select, or shorter bodies

Real scenarios: shutdown that takes seconds under load; a control channel ignored while a data flood is processed; a fan-in where one chatty producer dominates the output; a heartbeat case delayed by long jobs and the supervisor declaring the worker dead.

Draining after cancellation Important ​

In plain words: When a loop stops, there may be items still sitting in its channel's buffer. Decide on purpose: process them, hand them back, or drop them, and in each case make sure no sender is left blocked.

Common misunderstanding: "Drain with for v := range ch." That waits for the channel to be closed; if the producer is also shutting down and never closes, the drain hangs. A drain after cancellation is non-blocking: a select with default that stops when the buffer is empty.

Definition: Two different jobs share the name. (1) Graceful drain: the consumer, on ctx.Done(), processes whatever is buffered right now (Worker.drain), bounded by a shutdown deadline. (2) Unblocking drain: after an early return, keep receiving and discarding until the producer closes, so producers blocked on a send can exit (the "drain the channel" step in the pipelines blog; with ctx.Done() cases in the producers it is usually unnecessary).

1  jobs buffer: [J1 J2 J3 J4 J5]
2  cancel()
3  worker: case <-ctx.Done() -> drain (non-blocking): J1..J5 processed
4  buffer empty -> default -> return ctx.Err()
5  producer: its next send has a ctx.Done() case -> returns, no leak

Real scenarios: a Kubernetes pod with a 30-second termination grace period that must finish in-flight jobs; an in-memory batch that must be flushed to the database on shutdown; an HTTP server Shutdown that waits for active handlers (net/http: Server, Client).

Closing versus signalling, and sync.Cond Important ​

In plain words: Sending a value wakes one receiver. Closing a channel wakes all receivers, now and in the future. sync.Cond can wake one (Signal) or all (Broadcast) too, but it cannot be used in a select, so it cannot be combined with a timeout or a context.

Common misunderstanding: "Close the channel to say 'one item is ready'." Close is a one-time, permanent state change; it cannot be undone or repeated (close of closed channel panic). Use close for events that happen once (done, ready, shutdown); use sends for repeated items.

Definition: The sync.Cond documentation itself says: "For many simple use cases, users will be better off using channels than a Cond (Broadcast corresponds to closing a channel, and Signal corresponds to sending on a channel)." Cond.Wait must be called with the lock held and inside a loop that re-checks the condition. A one-shot event is close guarded by sync.Once (the Event type); its Done() channel works in any select.

NeedChannel waysync.Cond way
Wake one waiter per itemsend on a channelSignal()
Wake all, onceclose(ch)Broadcast() plus a flag
Wake all, repeatedlynew channel per generation, close the oldBroadcast()
Wait with timeout or cancelselect with ctx.Done()not possible directly
Waiters re-check statenot needed for closerequired loop around Wait
Event.Fire()  -> close(ch) once (sync.Once)
10 waiters    -> all wake; late waiter -> Done() already ready
CondGate      -> Open(): lock, open=true, unlock, Broadcast(); waiters loop on !open

Real scenarios: "service ready" gates in tests; configuration loaded once; a shutdown broadcast; a bounded buffer with many producers and consumers waiting on "not full" and "not empty" (one of the few places sync.Cond is reasonable). More in sync & atomic.

go
// Package event compares two ways to wake many waiters: closing a
// channel (works inside select, with timeouts and cancellation) and
// sync.Cond (needs a lock and a loop, cannot be used in select).
package event

import (
	"context"
	"sync"
)

// Event is a one-shot broadcast: Fire closes the channel once, and every
// current and future receive on Done proceeds immediately.
type Event struct {
	once sync.Once
	ch   chan struct{}
}

// New returns an unfired Event.
func New() *Event { return &Event{ch: make(chan struct{})} }

// Fire signals all waiters. Calling it twice is safe (sync.Once); a
// second close(ch) would panic with "close of closed channel".
func (e *Event) Fire() { e.once.Do(func() { close(e.ch) }) }

// Done is the channel to put in a select case.
func (e *Event) Done() <-chan struct{} { return e.ch }

// Wait blocks until the event fires or ctx ends.
func (e *Event) Wait(ctx context.Context) error {
	select {
	case <-e.ch:
		return nil
	case <-ctx.Done():
		return ctx.Err()
	}
}

// CondGate is the sync.Cond version of the same gate.
type CondGate struct {
	mu   sync.Mutex
	cond *sync.Cond
	open bool
}

// NewCondGate returns a closed gate.
func NewCondGate() *CondGate {
	g := &CondGate{}
	g.cond = sync.NewCond(&g.mu)
	return g
}

// Open wakes every waiter.
func (g *CondGate) Open() {
	g.mu.Lock()
	g.open = true
	g.mu.Unlock()
	g.cond.Broadcast()
}

// Wait blocks until Open. It cannot time out or observe a context:
// Cond.Wait has no select form.
func (g *CondGate) Wait() {
	g.mu.Lock()
	for !g.open { // always re-check the condition after waking
		g.cond.Wait()
	}
	g.mu.Unlock()
}

errgroup with select Good to know ​

In plain words: errgroup.WithContext starts goroutines, cancels a shared context at the first error and returns that error from Wait. It only works if every goroutine's blocking steps also select on that context.

Common misunderstanding: "errgroup stops the other goroutines." It cancels their context. A goroutine blocked on in <- it without a ctx.Done() case keeps blocking, and Wait never returns. The test TestPipelineFirstErrorCancelsOthers passes only because the producer's send selects on ctx.Done().

Definition: From the package source: "The derived Context is canceled the first time a function passed to Go returns a non-nil error or the first time Wait returns, whichever occurs first." Wait "blocks until all function calls from the Go method have returned, then returns the first non-nil error". The package is golang.org/x/sync/errgroup (the snippet pins v0.19.0, the last release that declares go 1.24.0). Limits (SetLimit) and pool design are in Worker Pools, Pipelines, Fan-Out/Fan-In, errgroup.

producer  select { in <- it ; <-ctx.Done() }
worker    item -1 -> return ErrBadItem       -> errgroup cancels ctx
producer  ctx.Done ready -> return ctx.Err()
consumer  out closed by worker's defer -> return nil
Wait()    -> "item -1: bad item"

Real scenarios: fetching several backends for one page and failing fast; parallel file processing where one corrupt file aborts the batch; a three-stage pipeline where any stage failing stops the rest.

go
// Package groups shows select inside errgroup goroutines: every blocking
// step also watches the group's context, so the first error cancels the
// rest and Wait returns promptly.
package groups

import (
	"context"
	"errors"
	"fmt"

	"golang.org/x/sync/errgroup"
)

// ErrBadItem is returned by the processing stage for a negative item.
var ErrBadItem = errors.New("bad item")

// Pipeline produces items, squares them in a worker, and sums results.
// The first error (or the caller's cancellation) stops every goroutine.
func Pipeline(ctx context.Context, items []int) (int, error) {
	g, ctx := errgroup.WithContext(ctx)
	in := make(chan int)
	out := make(chan int)

	g.Go(func() error { // producer
		defer close(in)
		for _, it := range items {
			select {
			case in <- it:
			case <-ctx.Done():
				return ctx.Err()
			}
		}
		return nil
	})

	g.Go(func() error { // worker
		defer close(out)
		for it := range in {
			if it < 0 {
				return fmt.Errorf("item %d: %w", it, ErrBadItem)
			}
			select {
			case out <- it * it:
			case <-ctx.Done():
				return ctx.Err()
			}
		}
		return nil
	})

	sum := 0
	g.Go(func() error { // consumer
		for v := range out {
			sum += v
		}
		return nil
	})

	err := g.Wait()
	return sum, err
}

Mechanics ​

Error texts you will see Must-know ​

Every text below was produced on Go 1.27.4 by the probes and snippets for this page.

SituationExact text
Case is not a channel operationselect case must be send or receive (possibly with assignment) (older gc compilers printed select case must be receive, send or assign recv; search for both)
Two default casesmultiple defaults (first at c/main.go:7:2)
Every goroutine blockedfatal error: all goroutines are asleep - deadlock!
Goroutine state in that report, empty selectgoroutine 1 [select (no cases)]:
Goroutine state, select with casesgoroutine 1 [select]:
Goroutine state, single-case select (compiled as a plain receive)goroutine 1 [chan receive]:
Send on a closed channel (also inside select)panic: send on closed channel
Closing twicepanic: close of closed channel
Closing nilpanic: close of nil channel
Context cancelledcontext canceled
Context deadlinecontext deadline exceeded
Discarded cancel func (go vet)the cancel function returned by context.WithTimeout should be called, not discarded, to avoid a context leak
Ticker with zero periodpanic: non-positive interval for NewTicker
Data race on loop state shared with another goroutineWARNING: DATA RACE then Read at ... by main goroutine: and Previous write at ... by goroutine 5:

Deadlock detection only fires when every goroutine is blocked. In a server with a running listener, a leaked goroutine stuck in [select] is silent; find it with a goroutine dump (SIGQUIT, /debug/pprof/goroutine?debug=2) or with the goroutineleak profile, generally available in Go 1.27: "A leaked goroutine is a goroutine blocked on some concurrency primitive (channels, sync.Mutex, sync.Cond, etc) that cannot possibly become unblocked." It is detected "using the garbage collector: if a goroutine G is blocked on concurrency primitive P, and P is unreachable from any runnable goroutine ... then P cannot be unblocked". The deadlock tests in the snippet re-run the test binary as a child to capture the real report:

go
package deadlock

import (
	"os"
	"os/exec"
	"strings"
	"testing"
)

// TestMain lets the test binary re-run itself as a child that deadlocks.
func TestMain(m *testing.M) {
	switch os.Getenv("SELECT_DEADLOCK") {
	case "empty":
		Forever()
	case "nil":
		NilCases()
	}
	os.Exit(m.Run())
}

func TestDeadlockReports(t *testing.T) {
	for mode, state := range map[string]string{
		"empty": "[select (no cases)]",
		"nil":   "[select]",
	} {
		t.Run(mode, func(t *testing.T) {
			cmd := exec.Command(os.Args[0], "-test.run=^$")
			cmd.Env = append(os.Environ(), "SELECT_DEADLOCK="+mode)
			out, err := cmd.CombinedOutput()
			if err == nil {
				t.Fatal("child exited cleanly; expected a fatal error")
			}
			s := string(out)
			if !strings.Contains(s, "fatal error: all goroutines are asleep - deadlock!") {
				t.Fatalf("missing deadlock message:\n%s", s)
			}
			if !strings.Contains(s, "goroutine 1 "+state) {
				t.Fatalf("missing goroutine state %s:\n%s", state, s)
			}
		})
	}
}

Inside the runtime Good to know ​

The compiler turns a select into a call to runtime.selectgo with an array of scase (channel plus element pointer) on the goroutine's stack, except for the special forms it rewrites: zero cases (block()), one case (a plain send or receive), one case plus default (selectnbsend/selectnbrecv). selectgo then:

StepWhat it does
Permutebuilds pollorder, a random permutation of non-nil cases (cheaprandn)
Lock ordersorts cases by channel address into lockorder so concurrent selects lock channels in the same order and cannot deadlock each other
Lock alllocks every channel involved (sellock)
Pass 1walks pollorder; the first case that can proceed wins (waiting sender/receiver, buffered data or room, closed channel)
Defaultif none can proceed and the select is non-blocking, unlock and return the default
Pass 2enqueue a sudog for this goroutine on every channel's wait queue, then gopark (state [select])
Wakethe channel that completed the operation wakes the goroutine
Pass 3lock again, dequeue the sudogs from every other channel, unlock, return the case index

The number of cases is capped at 65536 ("the number of scases is capped at 65536"), the same cap reflect.Select documents. Memory-model consequence: a successful case is an ordinary channel communication, so "A send on a channel is synchronized before the completion of the corresponding receive from that channel", and writes before close(done) are visible to any goroutine whose case <-done: ran.

Benchmarks Good to know ​

Single goroutine, buffered channels, testing.B.Loop, Apple M4 Pro, Go 1.27.4, one run. The two-case and four-case numbers include one buffered send per iteration (about 7 ns of the plain send/receive pair).

Benchmarkns/opallocs/opReading
PlainSendRecv (send + receive)14.390baseline channel cost
SelectOneCaseDefault (empty, default runs)2.710compiled to selectnbrecv: very cheap
SelectTwoCases (send + 2-case select)34.560lock two channels, permute
SelectFourCases (send + 4-case select)66.780cost grows with case count
ReflectSelectTwoCases (send + reflect)54.051reflection and an allocation

Conclusion: a select costs tens of nanoseconds and grows with the number of cases; it matters only in loops doing millions of operations per second, where batching (send slices, not items) helps more than micro-tuning.

go
package bench

import (
	"reflect"
	"testing"
)

// All benchmarks run in one goroutine on buffered channels so they
// measure the select machinery, not goroutine scheduling.

func BenchmarkPlainSendRecv(b *testing.B) {
	c := make(chan int, 1)
	for b.Loop() {
		c <- 1
		<-c
	}
}

func BenchmarkSelectOneCaseDefault(b *testing.B) {
	c := make(chan int, 1) // empty: default runs every time
	n := 0
	for b.Loop() {
		select {
		case <-c:
		default:
			n++
		}
	}
	_ = n
}

func BenchmarkSelectTwoCases(b *testing.B) {
	c := make(chan int, 1)
	quit := make(chan struct{})
	for b.Loop() {
		c <- 1
		select {
		case <-c:
		case <-quit:
		}
	}
}

func BenchmarkSelectFourCases(b *testing.B) {
	c := make(chan int, 1)
	q1, q2, q3 := make(chan struct{}), make(chan struct{}), make(chan struct{})
	for b.Loop() {
		c <- 1
		select {
		case <-c:
		case <-q1:
		case <-q2:
		case <-q3:
		}
	}
}

func BenchmarkReflectSelectTwoCases(b *testing.B) {
	c := make(chan int, 1)
	quit := make(chan struct{})
	cases := []reflect.SelectCase{
		{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(c)},
		{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(quit)},
	}
	for b.Loop() {
		c <- 1
		reflect.Select(cases)
	}
}

Solving the classic problems ​

ProblemSolutionHowCost or limit
Wait for one value with a limitselect with time.AfterRecvTimeoutOne timer per call
Wait that the caller can cancelselect with ctx.Done()RecvCtxCaller must create and cancel the context
Idle timeout in a loopone Timer, Reset per messageIdleLoopNeeds go.mod 1.23+ for the simple Reset
Total deadline for a looptimer created before the loopCollectForNone
Goroutine leaks on sendctx.Done() case, or buffer of 1 for a single resultMerge, the handler in GoEvery send needs the case
Merge inputs finishing at different timesnil the closed channelsMerge2Fixed number of inputs
Merge N inputsgoroutine per input + WaitGroupMergeN goroutines
Merge a run-time set in one goroutinereflect.SelectMergeReflectSlower, untyped
Full channeldrop, timeout or backpressurebounded.QueueProduct decision
Preferred channeltwo-step selectpriority.NextNot strict at the same wake-up
Don't start work after cancelctx.Err() before selectStopFirstOne extra check
Stop a loop and get its errorclosing chan chan errorPoller.CloseOne more channel
Graceful shutdownfor-select with ctx, ticker, jobs, drainWorker.RunDrain must be bounded by a deadline
One-shot broadcastclose under sync.Onceevent.EventCannot be reset
Fail fast across goroutineserrgroup + ctx.Done() casesgroups.Pipelinex/sync dependency

A worker with graceful shutdown Must-know ​

Worker.Run is the end-to-end pattern: one goroutine, three cases, and every exit is a return. Shutdown in production is two contexts: the "stop taking work" context (from signal.NotifyContext) that the loop watches, and a "finish within N seconds" deadline around the drain so a stuck job cannot hold the pod past its grace period.

go
stop, cancel := signal.NotifyContext(context.Background(), syscall.SIGTERM, os.Interrupt)
defer cancel()
w := &forselect.Worker{Jobs: jobs, Heartbeat: 10 * time.Second, Process: handle, Drain: true}
err := w.Run(stop) // returns context.Canceled after draining what was buffered
log.Printf("worker stopped: %v", err)
go
package forselect

import (
	"context"
	"errors"
	"sync"
	"sync/atomic"
	"testing"
	"time"
)

func TestWorkerGracefulShutdownDrains(t *testing.T) {
	jobs := make(chan Job, 10)
	var done []int
	var mu sync.Mutex
	w := &Worker{
		Jobs:      jobs,
		Heartbeat: time.Hour,
		Process: func(j Job) {
			mu.Lock()
			done = append(done, j.ID)
			mu.Unlock()
		},
		Drain: true,
	}
	ctx, cancel := context.WithCancel(context.Background())
	cancel() // cancelled before any job is taken
	for i := range 5 {
		jobs <- Job{ID: i}
	}
	err := w.Run(ctx)
	if !errors.Is(err, context.Canceled) {
		t.Fatalf("err = %v", err)
	}
	mu.Lock()
	defer mu.Unlock()
	if len(done) != 5 {
		t.Fatalf("drain processed %d of 5 buffered jobs", len(done))
	}
}

func TestWorkerExitsWhenJobsClosed(t *testing.T) {
	jobs := make(chan Job)
	var n atomic.Int32
	w := &Worker{Jobs: jobs, Heartbeat: time.Hour, Process: func(Job) { n.Add(1) }}
	errc := make(chan error, 1)
	go func() { errc <- w.Run(context.Background()) }()
	jobs <- Job{ID: 1}
	jobs <- Job{ID: 2}
	close(jobs)
	if err := <-errc; err != nil || n.Load() != 2 {
		t.Fatalf("err=%v n=%d", err, n.Load())
	}
}

func TestWorkerHeartbeat(t *testing.T) {
	var beats atomic.Int32
	w := &Worker{Jobs: make(chan Job), Heartbeat: 5 * time.Millisecond, Process: func(Job) {},
		OnBeat: func() { beats.Add(1) }}
	ctx, cancel := context.WithTimeout(context.Background(), 60*time.Millisecond)
	defer cancel()
	if err := w.Run(ctx); !errors.Is(err, context.DeadlineExceeded) {
		t.Fatalf("err = %v", err)
	}
	if beats.Load() < 3 {
		t.Fatalf("only %d heartbeats in 60ms at 5ms", beats.Load())
	}
}

func TestTickerReset(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	set := make(chan time.Duration)
	out := make(chan int, 100)
	go Beats(ctx, time.Hour, set, out)
	set <- 5 * time.Millisecond // from "never" to every 5 ms
	time.Sleep(60 * time.Millisecond)
	cancel()
	if n := len(out); n < 3 {
		t.Fatalf("only %d beats after Reset to 5ms", n)
	}
}

func TestPollerClose(t *testing.T) {
	calls := 0
	p := NewPoller(2*time.Millisecond, func() (int, error) {
		calls++ // only the loop goroutine touches calls
		if calls == 3 {
			return 0, ErrFetch
		}
		return calls, nil
	})
	first := <-p.Updates
	if first != 1 {
		t.Fatalf("first update %d", first)
	}
	time.Sleep(20 * time.Millisecond)
	if err := p.Close(); !errors.Is(err, ErrFetch) {
		t.Fatalf("Close = %v, want ErrFetch", err)
	}
	for range p.Updates { // closed by the loop; drains nothing or a few
	}
}

func TestBusyLoopSpins(t *testing.T) {
	spins := BusyPoll(StopAfter(20 * time.Millisecond))
	wakeups := BlockingWait(StopAfter(20 * time.Millisecond))
	if spins < 10000 {
		t.Fatalf("busy loop spun only %d times in 20ms", spins)
	}
	if wakeups != 1 {
		t.Fatalf("blocking wait woke %d times", wakeups)
	}
	t.Logf("busy loop: %d iterations in 20ms; blocking select: %d wake-up", spins, wakeups)
}

Timeout for a whole conversation versus each message Important ​

Decide which one the requirement means and put the timer in the matching place: per message ("the peer must answer each request within 2 s") is a timer created or Reset inside the loop; whole conversation ("the import must finish within 1 minute") is created once before the loop or comes from context.WithTimeout at the top. Many systems need both: a ctx deadline for the total and an idle Timer for silence.

Testing select code Must-know ​

Test goalTechnique
A timeout pathshort real durations with wide margins (10 to 60 ms), or testing/synctest (Go 1.25) so time advances only when every goroutine is blocked
No goroutine leakthe test waits for the goroutine's return (an errc channel), never just sleeps
Random choiceassert the distribution over many runs, never the order of one run
Priorityfill buffered channels before calling, so both are ready
Deadlock textre-run the test binary as a child (TestMain switch on an env var) and assert the output
Data racesgo test -race; loop state touched only by the loop goroutine

Choosing ​

SituationUseExtra techniqueReason
One wait with a limitselect + time.AfternoneShort and correct on Go 1.23+
Caller decides the limitselect + ctx.Done()return ctx.Err()Propagates through layers
Silence detectionone time.NewTimer + Resetdefer t.Stop()One timer, correct meaning
Overall deadline in a looptimer before the loop or context.WithTimeoutnonetime.After in the loop means idle
Periodic work in a looptime.NewTicker caseTicker.Reset to adaptTicks drop for slow readers
Try without waitingselect + defaultcount the missesCheapest form
Waiting in a loopselect without defaultnoneParks instead of spinning
Inputs that close at different timesnil the channelloop while any is non-nilClosed is always ready
Many inputs, fixed at startgoroutine per inputWaitGroup closes outputTyped and simple
Inputs added at run timereflect.Selectremove closed casesOnly option in one goroutine
Important channel firsttwo-step priority selectctx.Err() check firstselect itself is random
Full buffer, data may be lostdrop on fullmetric for dropsNever blocks the producer
Full buffer, data must not be lostbackpressure with ctx.Done()bounded by deadlineSlows producer, no loss
Full buffer, request pathwait with timeout, then 503retry with jitter client-sideFail fast
Stop and confirmclosing chan chan errorClose() errorGets the final error
Many goroutines, first error winserrgroup.WithContextctx.Done() in every selectCancels the rest
Wake everyone onceclose(ch)sync.OnceWorks in select
Wait on a condition under a locksync.Condloop around WaitOnly when channels do not fit

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

In one process, select is how the program composes its own concurrency: each HTTP handler waits on its backend calls with r.Context(), a few long-lived for-select loops do background work (cache expiry with a Ticker, an outbox relay that polls every second, a metrics flusher that drops on full), and main waits on a signal context to start shutdown. The simplest correct usage: every goroutine has an exit case, every send has a ctx.Done() case, and timers are created where their meaning (per call, per idle period, per conversation) says. A worker that polls a jobs table on a ticker and drains on shutdown typically runs a query like:

sql
-- polled by the ticker case of the worker loop; SKIP LOCKED lets several workers share the table
SELECT id, payload
FROM jobs
WHERE status = 'pending' AND run_at <= now()
ORDER BY run_at
LIMIT 10
FOR UPDATE SKIP LOCKED;

Modular monolith and multiple databases ​

Modules communicate through in-process channels or interfaces, and select is where module boundaries meet: an orders module publishes onto a bounded channel that a notifications module consumes, and the publisher picks a policy explicitly (backpressure for order events, drop for analytics). Each module's loops take a context derived from the application's root context, so one cancellation stops every module in order. Per-module database pools (Connection Pooling) are waited on with the same context, because database/sql calls take a ctx: a request that times out releases its pool slot instead of queuing behind it.

Microservices ​

1  client -> gateway   deadline 2 s (gRPC timeout header / HTTP client Timeout)
2  gateway handler     ctx, cancel := context.WithTimeout(r.Context(), 1800ms)
3                      select { case res := <-callOrders(ctx): ... ; case <-ctx.Done(): 504 }
4  orders service      receives deadline 1.7 s remaining; its own selects use that ctx
5  client gives up     -> r.Context() done -> gateway's ctx done -> outgoing call cancelled

select does not cross the network, but its two inputs do: deadlines travel as durations in gRPC metadata or as client timeouts, and cancellation travels as a closed connection or a cancelled stream. Inside each service, those arrive as a context and end in a case <-ctx.Done():. Consumers of a broker are for-select loops over the client library's delivery channel, a shutdown context and an idle or heartbeat timer; scaling them out is Competing Consumers & Scaling Consumers. The retry side of timeouts (how many, how long, jitter) is Timeouts, Retries & Jitter; what happens when nobody times out is Cascading Failures.

Distributed data: replicas, caches and fan-in across nodes ​

Hedged and replicated reads are the 2010 blog's Query at system scale: send the same read to several replicas, select the first answer into a buffered channel, cancel the rest with a context. The buffer (or the ctx.Done() case in each sender) is what keeps the losing goroutines from leaking. Scatter-gather over shards is fan-in with a deadline: collect answers until the timer fires, then return partial results and mark the missing shards. Caches with background refresh use a for-select with a Ticker and a "refresh now" channel; replicas' lag means the first answer may be stale, a concern for Replication, Read Replicas & Failover, not for select.

Scaling path: 1x, 10x, 100x ​

Scaleselect concernAction
1x (one process, low traffic)correctness: exits, ctx.Done() on every send, timer placementtests with -race, leak checks in tests
10x (busy service)timer per request, goroutine per request waiting, busy loops showing in CPU profilesreuse timers, remove default from waiting loops, goroutineleak profile in staging
100x (hot loops, many services)select cost per item, fairness under floods, shutdown time under loadbatch items per send, move slow work out of the loop goroutine, ctx.Err() check before taking work, bounded drains
anyfull queuesan explicit drop, timeout or backpressure policy per channel, with metrics

Lab ​

Everything here runs on a laptop with Go 1.24 or later; no Docker. Outputs marked "(real)" were produced on the host while writing this page (Go 1.27.4, macOS arm64, Apple M4 Pro); timings vary between runs.

bash
cd docs/snippets/go/select-multiplexing/go
gofmt -l .                       # no output
go vet ./...                     # no output
go test -race -count=1 ./...     # ok for 10 packages (real)

1. The ten experiments (real) ​

bash
go run ./lab
# 1 random choice: first=50029 second=49971
# 2 TryRecv: empty, received(9), closed
# 3 evaluated: [chan ready chan blocked value] -> chose "recv ready"
# 4 closed case chosen 1000 of 1000 iterations
# 5 deadline once: 12 values in 30ms; time.After per loop: 50 values in 130ms
# 6 stale value after Reset: false
# 7 busy for-select with default: 1951218 iterations in 10ms
# 8 priority order: [100 101 102 0 1 2]
# 9 queue size 3, offered 10: kept=3 dropped=7
# 10 RecvCtx: context deadline exceeded
go
// Command lab prints the select experiments used on the chapter page.
// Run from the module root: go run ./lab
package main

import (
	"context"
	"fmt"
	"time"

	"academy/select-multiplexing/basics"
	"academy/select-multiplexing/bounded"
	"academy/select-multiplexing/forselect"
	"academy/select-multiplexing/priority"
	"academy/select-multiplexing/timeouts"
)

func main() {
	// 1. uniform random choice between two ready cases
	a, b := basics.CountChoices(100000)
	fmt.Printf("1 random choice: first=%d second=%d\n", a, b)

	// 2. non-blocking receive on empty, full and closed channels
	ch := make(chan int, 1)
	_, s1 := basics.TryRecv(ch)
	ch <- 9
	v, s2 := basics.TryRecv(ch)
	close(ch)
	_, s3 := basics.TryRecv(ch)
	fmt.Printf("2 TryRecv: %v, %v(%d), %v\n", s1, s2, v, s3)

	// 3. evaluation order of select operands
	trace, chosen := basics.EvaluationOrder()
	fmt.Printf("3 evaluated: %v -> chose %q\n", trace, chosen)

	// 4. closed channel spins if not set to nil
	fmt.Printf("4 closed case chosen %d of 1000 iterations\n", basics.SpinsOnClosed(1000))

	// 5. overall deadline vs time.After inside the loop
	src := func() <-chan int {
		out := make(chan int)
		go func() {
			defer close(out)
			for i := range 50 {
				out <- i
				time.Sleep(2 * time.Millisecond)
			}
		}()
		return out
	}
	start := time.Now()
	good := timeouts.CollectFor(src(), 30*time.Millisecond)
	tGood := time.Since(start).Round(10 * time.Millisecond)
	start = time.Now()
	bad := timeouts.CollectForBuggy(src(), 30*time.Millisecond)
	tBad := time.Since(start).Round(10 * time.Millisecond)
	fmt.Printf("5 deadline once: %d values in %v; time.After per loop: %d values in %v\n",
		len(good), tGood, len(bad), tBad)

	// 6. stale tick after Reset (go 1.24 module)
	fmt.Printf("6 stale value after Reset: %v\n", timeouts.StaleAfterReset())

	// 7. busy loop
	spins := forselect.BusyPoll(forselect.StopAfter(10 * time.Millisecond))
	fmt.Printf("7 busy for-select with default: %d iterations in 10ms\n", spins)

	// 8. priority
	high := make(chan int, 3)
	low := make(chan int, 3)
	for i := range 3 {
		high <- 100 + i
		low <- i
	}
	var order []int
	for range 6 {
		x, _, _ := priority.Next(context.Background(), high, low)
		order = append(order, x)
	}
	fmt.Printf("8 priority order: %v\n", order)

	// 9. bounded queue that drops on full
	q := bounded.New[int](3)
	for i := range 10 {
		q.Offer(i)
	}
	fmt.Printf("9 queue size 3, offered 10: kept=%d dropped=%d\n", len(q.C()), q.Dropped())

	// 10. ctx.Done error text
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Millisecond)
	defer cancel()
	_, err := timeouts.RecvCtx(ctx, make(chan int))
	fmt.Printf("10 RecvCtx: %v\n", err)
}

2. The deadlock report (real) ​

bash
go run ./deadlock/cmd/deadlock
# fatal error: all goroutines are asleep - deadlock!
#
# goroutine 1 [select (no cases)]:
# academy/select-multiplexing/deadlock.Forever(...)
go run ./deadlock/cmd/deadlock nil
# fatal error: all goroutines are asleep - deadlock!
#
# goroutine 1 [select]:
# academy/select-multiplexing/deadlock.NilCases(...)

3. The compile errors (real) ​

Put case f(): (a function call, not a channel operation) in a select, and in another file two default: cases:

bash
go build ./a
# a/main.go:8:8: select case must be send or receive (possibly with assignment)
go build ./c
# c/main.go:8:2: multiple defaults (first at c/main.go:7:2)

4. Benchmarks (real, single run) ​

bash
go test -run '^$' -bench . -benchmem ./bench
# BenchmarkPlainSendRecv-12            85504852   14.39 ns/op   0 B/op   0 allocs/op
# BenchmarkSelectOneCaseDefault-12    443930907    2.714 ns/op  0 B/op   0 allocs/op
# BenchmarkSelectTwoCases-12           34493991   34.56 ns/op   0 B/op   0 allocs/op
# BenchmarkSelectFourCases-12          18416264   66.78 ns/op   0 B/op   0 allocs/op
# BenchmarkReflectSelectTwoCases-12    21910237   54.05 ns/op   8 B/op   1 allocs/op

5. A goroutine leak in a long-running server (expected, not run) ​

Remove the case <-ctx.Done(): from the forwarder in fanin.Merge, build with Go 1.27, start a server that calls Merge per request and abandons the output early, then:

bash
curl -s localhost:6060/debug/pprof/goroutineleak?debug=1 | head
# expected: a stack ending in fanin.Merge[...].func1 blocked in "chan send",
# with a count that grows with every abandoned request

6. Timer semantics on an old module (expected, not run) ​

With go 1.22 in go.mod and a Go 1.23 to 1.26 toolchain, StaleAfterReset returns true (the fired value stays in the one-slot buffer and is received right after Reset). With go 1.24 in go.mod, or any module on Go 1.27 where asynctimerchan was removed, it returns false, which is what experiment 6 printed.

Common misconceptions ​

BeliefReality
Cases are tried top to bottomReady cases are chosen uniformly at random
Only the winning case's expressions runAll channel operands and send values are evaluated on entry
default makes a loop efficientIt makes a waiting loop spin
A closed channel case fires onceIt is ready on every iteration until you nil it
A nil channel in a case is a bugIt is the standard way to disable a case
default protects a send on a closed channelThe send still panics: send on closed channel
time.After always leaksUnreferenced timers are collected on go.mod 1.23+ and on Go 1.27
time.After in a loop is an overall timeoutIt restarts every iteration: an idle timeout
After Stop you must drain t.CNot on Go 1.23+ semantics; the drain can now block forever
cancel() stops the goroutineIt closes Done; the goroutine must select on it
break leaves the for-selectIt leaves the select; use return or a label
Putting a case first gives it priorityUse a two-step select
select {} keeps a server alive safelyOnly if other goroutines run; otherwise deadlock, and it has no shutdown path
reflect.Select is fine for any fan-inIt is slower, untyped and capped at 65536 cases
sync.Cond and channels are interchangeableCond.Wait cannot be combined with a timeout or context in a select

Cheat sheet ​

TopicWhat to remember
ChoiceRandom among ready; default if none; else block
EvaluationAll operands once, source order, on entry
Try-receiveselect { case v, ok := <-c: ...; default: }
Try-sendselect { case c <- v: ...; default: }; closed still panics
Nil channelNever ready; set to nil to disable a case
Closed channelAlways ready; zero value and ok == false after buffered values
One timeoutcase <-time.After(d):
Idle timeoutt := time.NewTimer(d); t.Reset(d) after each event
Total deadlineTimer before the loop or context.WithTimeout
Cancellationcase <-ctx.Done(): return ctx.Err() on every blocking step
Loop exitreturn from a case; break only leaves select
Busy loopNo default in a loop that only waits
Heartbeattime.NewTicker; Ticker.Reset(d) to change period; non-blocking send of the beat
PriorityNon-blocking try of the preferred channel, then full select
Full channelDrop (default), timeout (timer), backpressure (ctx.Done())
Fan-inGoroutine per input + WaitGroup closes output
Dynamic casesreflect.Select, max 65536
Broadcastclose once under sync.Once
Deadlock textfatal error: all goroutines are asleep - deadlock!
Leak huntingGoroutine dump, goroutineleak profile (Go 1.27)

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Two cases are ready and there is a default. Which runs? Must-know ​

Answer

Answer: One of the two ready cases, chosen uniformly at random. default runs only when no case can proceed.

2 — In case out <- compute():, is compute() called when another case wins? Important ​

Answer

Answer: Yes. Every channel operand and send value is evaluated once, in source order, on entry to the select, regardless of which case is chosen.

3 — What does a receive case on a nil channel do, and why is that useful? Must-know ​

Answer

Answer: It is never ready. Assigning nil to a channel variable disables its case, for example after the input was closed in a merge loop.

4 — A loop handles ok == false from a closed input with continue. What happens? Must-know ​

Answer

Answer: The closed channel is ready on every iteration, so the loop spins, choosing that case again and again. Set the variable to nil or return.

5 — Why does case <-time.After(30 * time.Second): inside a for-select fail as a 30-second overall limit? Must-know ​

Answer

Answer: Each iteration evaluates time.After again and starts a new 30-second timer, so the limit restarts after every message. Create the timer before the loop or use context.WithTimeout.

6 — On a module with go 1.24, do you need to drain t.C after t.Stop() before t.Reset(d)? Good to know ​

Answer

Answer: No. Since Go 1.23 timer channels are unbuffered and no stale value is received after Stop or Reset; a drain receive could now block forever.

7 — You call cancel() but a goroutine never exits. What is the likely cause? Must-know ​

Answer

Answer: It is blocked on a send or receive that has no case <-ctx.Done(): (or never checks ctx.Err()). Cancellation only closes the Done channel.

8 — How do you make channel high win over low whenever it has data? Important ​

Answer

Answer: First a non-blocking select on high alone; if it hits default, a blocking select on high, low and ctx.Done().

9 — When is drop-on-full the right policy, and when is backpressure? Must-know ​

Answer

Answer: Drop when losing an item is acceptable and the producer must never block (metrics, logs, latest-value streams). Backpressure when the item must not be lost and slowing the producer is acceptable (jobs, orders, pipeline stages).

10 — Why can sync.Cond not replace a done channel in a worker loop? Important ​

Answer

Answer: Cond.Wait is not a channel operation, so it cannot be a select case and cannot be combined with a timeout, a ticker or ctx.Done().

11 — What does fatal error: all goroutines are asleep - deadlock! tell you, and why do servers rarely print it? Must-know ​

Answer

Answer: Every goroutine is blocked and none can wake another. Servers usually have a goroutine blocked in network I/O or a timer pending, so a single leaked goroutine stays silent; use goroutine dumps or the goroutineleak profile.

12 — Why does errgroup's first error not stop a producer blocked on in <- v? Important ​

Answer

Answer: errgroup only cancels the shared context. The producer must select on ctx.Done() next to its send to notice.

Glossary ​

TermMeaning
selectStatement that runs one of several channel communications
caseOne send or receive inside a select
defaultCase that runs when no communication can proceed; makes the select non-blocking
ready caseA case whose communication can proceed now
random selectionUniform pseudo-random choice among ready cases
non-blocking sendselect with a send case and default
non-blocking receiveselect with a receive case and default
nil channel caseCase on a nil channel; never ready
closed channel caseReceive case on a closed channel; always ready
timeoutA case that becomes ready after a duration
time.AfterFunction returning a channel that fires once after d
timer leakUnfired timers kept alive; fixed for unreferenced timers since Go 1.23
time.NewTimerCreates a stoppable, resettable one-shot timer
Timer.StopPrevents a timer from firing
Timer.ResetRe-arms a timer with a new duration
context.WithTimeoutChild context whose Done closes after a duration
ctx.DoneChannel closed when a context ends
for-select loopfor { select { ... } } event loop in one goroutine
busy loopLoop that spins because default never blocks
heartbeatPeriodic signal that a loop is alive
tickerRepeating timer channel
time.TickerType that sends the time every period
Ticker.ResetChanges a ticker's period (Go 1.15)
priority selectTwo-step select that prefers one channel
quit channelChannel used to tell a loop to stop
fan-inMerging many channels into one
bounded sendSend to a bounded buffer with a policy for full
drop on fullPolicy: discard the item when the buffer is full
backpressureProducer waits for consumer capacity
select {}Empty select; blocks forever
block foreverGoroutine parked with no way to wake
reflect.SelectSelect over a run-time slice of SelectCase
fairnessEqual chances for ready cases in one select
starvationA case or goroutine that waits indefinitely while others run
drainingTaking remaining buffered items after stop, without blocking
graceful shutdown loopWorker that stops taking work, drains, and returns
sync.CondCondition variable; Signal and Broadcast, not usable in select
errgroupgolang.org/x/sync/errgroup: goroutines with first-error cancellation
deadlockAll goroutines blocked; runtime aborts the program
goroutineleak profileGo 1.27 profile listing goroutines that can never unblock
stream_selectPHP function running the select() system call on stream arrays
event loopSingle thread dispatching I/O and timer callbacks
ReactPHPPHP library providing an event loop (react/event-loop)
SwoolePHP extension with coroutines and coroutine channels

For PHP/Laravel developers ​

PHP-FPM gives each request its own process, so a Laravel controller rarely waits on two things at once; when it must, it uses Http::pool, queue workers, or a separate process. The select idea exists in PHP at the I/O level: stream_select "Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by seconds and microseconds". ReactPHP builds an event loop on it ("ReactPHP's core reactor event loop that libraries can use for evented I/O"), with Loop::addReadStream, Loop::addTimer and futureTick. Swoole/OpenSwoole adds coroutines and a Coroutine\Channel whose push and pop take a timeout.

TaskPHPGo
Wait for whichever socket is readablestream_select($read, $write, $except, 2)select over channels fed by connection goroutines
Timeoutthe seconds/microseconds argumentscase <-time.After(d): or ctx.Done()
Timer callbackLoop::addTimer(1.0, fn) (ReactPHP)time.AfterFunc or a timer case
Periodic workLoop::addPeriodicTimertime.Ticker case
Channel with timeout$chan->pop(2.0) (Swoole)select with a timer case
Non-blocking trystream_select with timeout 0select with default
Cancellationclose the stream, stop the loopctx.Done()
Laravel job timeout#[Timeout(120)] on the job or queue:work --timeout=30 (the worker exits with an error)the job's own ctx deadline; the goroutine returns
php
$read = [$socketA, $socketB];
$write = $except = null;
// like select with two receive cases and a 2 s timeout case
$n = stream_select($read, $write, $except, 2);
if ($n === 0) { /* timeout */ }
foreach ($read as $ready) { /* like the case body for each ready socket */ }

The differences that matter: stream_select returns every ready stream and you loop over them, while Go runs exactly one random ready case per select; PHP's timeout is an argument of the call, while Go's is just another case; and the manual warns against a 0 timeout in a loop ("it is NOT a good idea to use a 0 timeout value in a loop as it will cause your script to consume too much CPU time"), the PHP version of the busy loop.

References ​

Fetchable pages were saved under the scratchpad sources/select-multiplexing/ folder; package documentation was read through go doc (Go 1.27.4) because pkg.go.dev returns HTTP 403 to non-browser clients.

Built by Morteza Negahi