Primitives
Go gives you goroutines, channels, select, context, sync and atomics. Each one has exact blocking rules. Here are the rules, recorded from real runs, and the cost of each primitive.
- 1Every goroutine needs a known way to exit. Before you write go, say what stops it.
- 2The goroutine that sends owns the channel, and only the owner closes it.
- 3A send or receive on a nil channel blocks forever. In a select, that disables the case.
- 4A mutex guards state. A channel moves work or signals an event. An atomic covers one word.
package main
import (
"fmt"
"runtime"
"time"
)
func fetch(slow <-chan struct{}) string {
ch := make(chan string)1
go func() {
<-slow
ch <- "ok"2
}()
select {
case v := <-ch:
return v
case <-time.After(time.Millisecond)3:
return "timeout"
}
}
func main() {
slow := make(chan struct{})
for range 100 {
fetch(slow)
}
close(slow)4
time.Sleep(100 * time.Millisecond)
fmt.Println("goroutines:", runtime.NumGoroutine())
}- 1Unbuffered: a send waits for a receiver.
- 2After the timeout no receiver exists. This goroutine stays here until the program ends.
- 3The caller leaves through this case and drops ch.
- 4Every slow call is now done, and each one tries to send.
| channel | recorded output | status |
|---|---|---|
| make(chan string) | goroutines: 101 | 100 leaked |
| make(chan string, 1) | goroutines: 1 | All exit |
- The buffered send always completes, so the goroutine always exits.
- The one remaining goroutine is main.
- The timeout works in both programs. Only the leak differs, so no test on the return value finds it.
- Each leaked goroutine keeps its stack and everything it references.
A goroutine that sends after its caller has left blocks forever. I give the send a buffer slot or a way out.
| cost | measured |
|---|---|
| Memory, parked | 2,722 B |
| Start and finish | 530 ns |
| One unbuffered handoff | 221 ns |
- The scheduler runs goroutines on GOMAXPROCS threads. A blocked goroutine parks and holds no thread.
- A stack starts small and grows by copying. The start size follows the average stack use.
- Memory is the runtime's total growth divided by 100,000 parked goroutines.
A goroutine costs about 3 KB and about one microsecond. One million parked goroutines use about 3 GB.
- An unbuffered channel is the same struct with no ring. Every send meets a receiver directly.
- Most operations take the lock and copy a value, so a channel costs more than a mutex (panel Z).
- Close sets a flag and wakes every parked goroutine in both queues.
A channel is a locked ring buffer with two queues of parked goroutines. A send to a waiting receiver skips the buffer.
| channel state | send | receive | close |
|---|---|---|---|
| nil | Blocks forever | Blocks forever | Panics close of nil channel |
| unbuffered, no partner | Blocks until a receive | Blocks until a send | Proceeds |
| buffer has room | Proceeds | Blocks until a send | Proceeds |
| buffer full | Blocks until a receive | Returns 1, true | Proceeds |
| closed, value left | Panics send on closed channel | Returns 1, true | Panics close of closed channel |
| closed, drained | Panics send on closed channel | Returns 0, false | Panics close of closed channel |
Each receive above uses the form v, ok := <-ch. The buffered channels have capacity 1 and hold the value 1.
Nil blocks, closed panics on send, and a closed channel gives zero values after its buffer drains. Close panics on nil and on closed.
| situation | status |
|---|---|
| One sender closes after its last send | Approved |
| Many senders; one goroutine waits for them, then closes | Approved |
| Close to tell many goroutines to stop | Use context |
| A receiver closes to stop the sender | Not approved |
| Each of many senders closes when it ends | Not approved |
| Close a channel only to free it | Not needed |
The garbage collector frees an unreachable channel, closed or not. Close is a signal to receivers.
The sender closes, because only the sender knows that no more values come. With many senders, a coordinator closes after a WaitGroup.
| situation | result |
|---|---|
| Several cases ready | One at random, so case order is not a priority. |
| No case ready, default present | Default runs at once. |
| No case ready, no default | Blocks until one is ready. |
| Case on a nil channel | Never ready. Use it to turn a case off. |
| Receive on a closed channel | Always ready. A loop spins until you set it to nil. |
| select with no cases | Blocks forever. |
A timeout is a case on a timer channel. For a priority, check the urgent channel first in a non-blocking select.
Select picks at random among ready cases. Default makes it non-blocking, and a nil channel removes a case.
| rule | why | status |
|---|---|---|
| Pass ctx as the first parameter of each function on the call path | Each call can stop at the same signal, and readers find it in one place. | Approved |
| Call cancel on every path, usually with defer | The child stays attached to its parent until cancel runs. go vet reports a lost cancel. | Approved |
| Select on ctx.Done beside every blocking send and receive | A goroutine that never looks at ctx cannot stop. | Approved |
| Use WithTimeoutCause or WithCancelCause, and read context.Cause | Err only says canceled or deadline exceeded. Cause says why. | Approved |
| Use WithoutCancel for work that must outlive the request | It keeps the values and drops the cancel. Add a new timeout to it. | Audit logs, cleanup |
| Store request-scoped data in values: trace ID, request ID | The data crosses APIs that do not know about it. | Request-scoped only |
| Put a context in a struct field | The struct outlives the call, and the deadline no longer matches the work. | Not approved |
| Pass optional parameters in values | The compiler cannot check them, and the signature hides them. | Not approved |
Context goes first because every blocking call on the path needs it. I cancel with a cause, so the log says why the work stopped.
| situation | use | mutex | channel |
|---|---|---|---|
| Guard a map or a struct | sync.Mutex | Approved | Slower, more code |
| Keep invariants across several fields | sync.Mutex | Approved | Not approved |
| Hand one unit of work to another goroutine | chan | Not approved | Approved |
| Queue work between stages, with backpressure | buffered chan | Not approved | Approved |
| Tell many goroutines to stop | context or close | Not approved | Approved |
| Wait with a timeout or with cancellation | select | Lock cannot time out | Approved |
| Limit concurrent work | buffered chan | Not approved | Approved |
| Count one number from many goroutines | atomic.Int64 | If it joins other fields | Not approved |
| Swap a read-mostly config | atomic.Pointer | If readers need two fields to agree | Not approved |
| Wait for N goroutines to finish | sync.WaitGroup | Not approved | Not approved |
A mutex protects state. A channel transfers ownership of work or signals an event. I choose by what the goroutines share.
| type | use it for | avoid it when |
|---|---|---|
| Mutex | Most shared state. Hold it for a few lines. | You hold it across I/O. Every other goroutine then waits for the I/O. |
| RWMutex | Reads that hold the lock for a long time: 135 ns against 930 ns with Mutex. | Writes dominate: 66.3 ns against 52.7 ns. A reader must not take RLock twice (see the drill). |
| Once | One-time setup with no result. | Setup can fail and you want a retry. A panic also counts as done. |
| OnceValue | Lazy values. OnceValues adds an error. OnceFunc has no result. | The error is temporary: the first result stays forever. |
| WaitGroup | Wait for a set of goroutines. Go does Add and Done for you. | You need the first error or a limit. Use errgroup (see G12). |
| Cond | Many goroutines wait for a state, and the state lives under a mutex. | A channel can express it. A Cond wait cannot take a timeout or a context. |
| Map | Keys that settle early, or goroutines that touch disjoint keys. Reads: 2.8 ns against 40.4 ns. | You need a typed API or one value across keys. A map and a mutex are simpler. |
| Pool | Hot, short-lived buffers: 27.5 ns and 0 allocations against 177 ns and 1. | You need a cache. The garbage collector empties a pool at any time. |
I start with Mutex. I move to RWMutex only for long reads, and to sync.Map only for keys that settle early.
// Generate owns out: it makes the channel, sends on it, and closes it.
func Generate(ctx context.Context, n int) <-chan int1 {
out := make(chan int)
go func() {
defer close(out)2
for i := range n3 {
select {
case out <- i:
case <-ctx.Done():4
return
}
}
}()
return out
}- 1The return type says the caller can only receive, so the caller cannot close it.
- 2Runs on both exits: the last value sent, or ctx ended. A range loop in the caller then ends.
- 3Range over an integer: Go 1.22.
- 4The way out. Without it, a caller that stops reading leaves this goroutine blocked forever.
The function that makes the channel starts the sender and closes the channel on every exit path.
// Drain reads both channels until both close.
func Drain(a, b <-chan int) []int {
var got []int
for a != nil || b != nil1 {
select {
case v, ok := <-a:
if !ok {
a = nil2
continue
}
got = append(got, v)
case v, ok := <-b:
if !ok {
b = nil
continue
}
got = append(got, v)
}
}
return got
}- 1The loop ends when both inputs are off.
- 2A closed channel is always ready, so the loop would spin. A nil channel is never ready.
When one input closes, I set its variable to nil. Select then stops looking at it, and the loop ends when both are nil.
// ErrSlowBackend says why a call ran out of time.
var ErrSlowBackend = errors.New("backend too slow")
// Call runs fn with a deadline and returns as soon as ctx ends.
func Call(
ctx context.Context, d time.Duration,
fn func(context.Context) (string, error),
) (string, error) {
ctx, cancel := context.WithTimeoutCause(ctx, d, ErrSlowBackend)1
defer cancel()2
type result struct {
v string
err error
}
done := make(chan result, 1)3
go func() {
v, err := fn(ctx)
done <- result{v, err}
}()
select {
case r := <-done:
return r.v, r.err
case <-ctx.Done():
return "", fmt.Errorf("call: %w", context.Cause(ctx)4)
}
}- 1The new context ends at d or with its parent, whichever is first. Cause reports ErrSlowBackend for the timeout.
- 2Releases the timer and the link to the parent, also on a fast return.
- 3One slot: this is the fix from panel A. The send always completes.
- 4Returns the parent's cause if the parent ended first, so the caller sees the real reason.
I derive a deadline with a cause, run the call in a goroutine, and buffer the result so that the goroutine can always exit.
type requestIDKey struct{}1
// WithRequestID returns a context that carries id.
func WithRequestID(ctx context.Context, id string) context.Context {
return context.WithValue(ctx, requestIDKey{}, id)
}
// RequestID returns the id in ctx, if there is one.
func RequestID(ctx context.Context) (string, bool) {
id, ok := ctx.Value(requestIDKey{}).(string)2
return id, ok
}- 1An unexported type: a value of it can only come from this package.
- 2Value returns any. The comma-ok form handles a missing key.
A context key is an unexported type, so no other package can collide with it.
// Config is a value that is slow to load.
type Config struct{ Addr string }
// NewLoader returns a function that calls read once and repeats its result.
func NewLoader(read func() (Config, error)) func() (Config, error) {
return sync.OnceValues(read)1
}- 1Concurrent callers wait for the first call. Every later call returns the stored result.
OnceValues replaces a mutex, a flag and two fields. It runs once and repeats the result.
// ParallelMap applies f to each element in its own goroutine.
func ParallelMap[T, R any](in []T, f func(T) R) []R {
out := make([]R, len(in))2
var wg sync.WaitGroup
for i, v := range in {
wg.Go(func() { out[i] = f(v) })1
}
wg.Wait()3
return out
}- 1Go 1.25. Each iteration has its own i and v since Go 1.22, so the closure needs no arguments.
- 2Allocate before the goroutines start. Each goroutine writes one element, and elements are separate memory.
- 3The return from f synchronizes with this Wait, so reading out afterwards is safe.
This starts one goroutine per element. For a long list, set a limit (see G12).
WaitGroup.Go does the Add and the Done, so the classic misplaced Add cannot happen. Writing to separate slice elements needs no lock.
// Table is a map that many goroutines read and few write.
type Table struct {
mu sync.RWMutex
rows map[string]string
}
// NewTable returns an empty table.
func NewTable() *Table { return &Table{rows: make(map[string]string)} }
// Get returns the row for key.
func (t *Table) Get(key string) (string, bool) {
t.mu.RLock()1
defer t.mu.RUnlock()
v, ok := t.rows[key]
return v, ok
}
// Set stores the row for key.
func (t *Table) Set(key, value string) {
t.mu.Lock()2
defer t.mu.Unlock()
t.rows[key] = value
}- 1Readers share the lock. A waiting writer blocks new readers.
- 2One writer, with no readers.
RWMutex lets readers run together. It gains most on long reads and loses when writes dominate, so I measure first.
// Queue is a bounded FIFO. Get and Put wait instead of failing.
type Queue[T any] struct {
mu sync.Mutex
nonEmpty *sync.Cond
nonFull *sync.Cond
items []T
limit int
closed bool
}
// NewQueue returns a queue that holds at most limit items.
func NewQueue[T any](limit int) *Queue[T] {
q := &Queue[T]{limit: limit}
q.nonEmpty = sync.NewCond(&q.mu)
q.nonFull = sync.NewCond(&q.mu)
return q
}
// Put waits for room, then adds v. It reports false after Close.
func (q *Queue[T]) Put(v T) bool {
q.mu.Lock()
defer q.mu.Unlock()
for len(q.items) == q.limit && !q.closed1 {
q.nonFull.Wait()2
}
if q.closed {
return false
}
q.items = append(q.items, v)
q.nonEmpty.Signal()3
return true
}
// Get waits for an item. It reports false when the queue is closed and empty.
func (q *Queue[T]) Get() (T, bool) {
q.mu.Lock()
defer q.mu.Unlock()
for len(q.items) == 0 && !q.closed {
q.nonEmpty.Wait()
}
var v T
if len(q.items) == 0 {
return v, false
}
v, q.items = q.items[0], q.items[1:]
q.nonFull.Signal()
return v, true
}
// Close wakes every waiter.
func (q *Queue[T]) Close() {
q.mu.Lock()
defer q.mu.Unlock()
q.closed = true
q.nonEmpty.Broadcast()4
q.nonFull.Broadcast()
}- 1Always a loop: another goroutine can take the slot before this one runs.
- 2Releases the mutex while it waits, and takes it again before it returns.
- 3One new item wakes one reader.
- 4Close changes the state for every waiter, so wake all of them.
Cond waits in a loop on a state under the mutex. Signal wakes one goroutine, and Broadcast wakes all of them.
// Counters is a set of named counters. The names settle early.
type Counters struct{ m sync.Map }
// Inc adds one to the named counter.
func (c *Counters) Inc(name string) {
v, ok := c.m.Load(name)1
if !ok {
v, _ = c.m.LoadOrStore(name, new(atomic.Int64))2
}
v.(*atomic.Int64).Add(1)
}
// Get returns the named counter.
func (c *Counters) Get(name string) int64 {
v, ok := c.m.Load(name)
if !ok {
return 0
}
return v.(*atomic.Int64).Load()
}- 1The common path: no allocation.
- 2Two goroutines can race here. Both get the one stored counter.
sync.Map suits keys that settle early. The value type is any, so I wrap it in a small typed struct.
var buffers = sync.Pool{New: func() any { return new(bytes.Buffer) }}
// Greeting builds a string in a reused buffer.
func Greeting(name string) string {
b := buffers.Get().(*bytes.Buffer)
b.Reset()1
defer buffers.Put(b)2
b.WriteString("hello, ")
b.WriteString(name)
return b.String()3
}- 1A pooled object keeps its old contents. Reset it before use.
- 2After Put, another goroutine can have the buffer. Do not keep a reference.
- 3String copies the bytes, so the result survives the Put.
A pool reuses buffers on a hot path. I reset on Get, I never keep a pointer after Put, and I expect it to be empty at any time.
// Limits is an immutable value: replace it, never change it.
type Limits struct{ MaxBytes int }
// Gate reads its limits on every request and takes no lock.
type Gate struct {
limits atomic.Pointer[Limits]1
served atomic.Int642
}
// NewGate returns a gate with the first limits.
func NewGate(l Limits) *Gate {
g := &Gate{}
g.limits.Store(&l)3
return g
}
// Allow admits a request of the given size and counts it.
func (g *Gate) Allow(size int) bool {
if size > g.limits.Load().MaxBytes {
return false
}
g.served.Add(1)
return true
}
// Update replaces the limits for every later Allow.
func (g *Gate) Update(l Limits) { g.limits.Store(&l) }
// Served returns how many requests passed.
func (g *Gate) Served() int64 { return g.served.Load() }- 1Typed since Go 1.19: no unsafe.Pointer, and no plain read of the value can compile.
- 2Always aligned to 64 bits, also on 32-bit systems.
- 3Copy on write. Each Limits value stays immutable after Store.
Go atomics are sequentially consistent. There are no relaxed forms to choose from.
Readers load a pointer to an immutable value with no lock. A writer builds a new value and swaps the pointer.
func TestCallDoesNotLeakOnTimeout(t *testing.T) {
synctest.Test1(t, func(t *testing.T) {
release := make(chan struct{})
slow := func(context.Context) (string, error) {
<-release
return "late", nil
}
_, err := Call(t.Context(), time.Millisecond, slow)
if !errors.Is(err, ErrSlowBackend) {
t.Fatalf("err = %v", err)
}
close(release)
// A bubble fails when a goroutine is blocked at its end.
synctest.Wait()2
})
}- 1Starts a bubble. Time jumps forward when every goroutine in the bubble blocks.
- 2Waits until every other goroutine in the bubble has blocked or exited.
A mutex wait is not durable in a bubble, because a goroutine outside could release the mutex. Run these tests with -race too.
I test timeouts inside a synctest bubble. Time is fake, so the test is instant and exact, and a stuck goroutine fails it.
t = 0 ms
The producer computes item 1.
The consumer blocks: the channel is empty.
- works
- blocked on send
- blocked on receive
- finished
- The producer needs 10 ms per item and the consumer needs 30 ms. Each cell is 10 ms.
- Capacity changes who waits, and when. The finish time does not change.
- Use a buffer for bursts, or for a known number of sends. Do not use one to hide a slow consumer.
A buffer moves the wait. It does not make a slow consumer faster: the run takes the same time at every capacity.
| since | what changed | what it means here |
|---|---|---|
| 1.19 | Typed atomics: atomic.Int64, atomic.Pointer[T]. The memory model is revised. Start stack size follows the average use. | Prefer these types to the function forms. |
| 1.20 | context.WithCancelCause and context.Cause. sync.Map gets Swap, CompareAndSwap and CompareAndDelete. | Cancel with a reason. |
| 1.21 | sync.OnceFunc, OnceValue, OnceValues. context.WithoutCancel, WithDeadlineCause, WithTimeoutCause, AfterFunc. | Most hand-written lazy init can go. |
| 1.22 | Each loop iteration creates new variables. Range over an integer. | The copy i := i before go is no longer needed. |
| 1.23 | Timer channels are unbuffered, and unreferenced timers are collected without Stop. sync.Map.Clear. atomic And and Or. | No stale value after Reset or Stop. len on a timer channel is 0. |
| 1.24 | New sync.Map implementation. testing.B.Loop. T.Context and B.Context. | Writes to disjoint keys contend less. |
| 1.25 | sync.WaitGroup.Go. testing/synctest. GOMAXPROCS follows the cgroup CPU limit on Linux and updates at run time. go vet reports a misplaced WaitGroup.Add. runtime/trace.FlightRecorder. | Container limits apply with no extra library. |
| 1.26 | signal.NotifyContext cancels with a cause that names the signal. The Green Tea collector is the default. goroutineleak profile as an experiment. | context.Cause tells you which signal stopped the server. |
| 1.27 | goroutineleak profile is generally available in runtime/pprof and at /debug/pprof/goroutineleak. synctest.Sleep. The asynctimerchan setting is gone, so timer channels are always unbuffered. | Find the leak from panel A in production. See G12 for a test. |
| when | the moment | what to do or say |
|---|---|---|
| build | The store has a map and concurrent requests. | Add a mutex to the store struct on the first line. Say why: net/http runs each request in its own goroutine. |
| build | A background sweep removes expired entries. | Use a ticker in a goroutine, with a select on ctx.Done. Keep the lock for the sweep short. |
| build | A test must prove the store is safe. | Start N goroutines with wg.Go, assert the invariant, run go test -race. |
| build | A handler calls something slow. | Pass r.Context() down. It ends when the client disconnects. |
| talk | "Why a mutex, not a channel?" | The goroutines share state, and they do not pass work. A channel here adds a goroutine and costs more per operation. |
| talk | "What stops this goroutine?" | Name the signal: ctx.Done, or a closed input channel. Then name the test that proves it. |
| talk | "How do you find a leak in production?" | Watch the goroutine count, then read the goroutineleak profile. It reports blocked goroutines that nothing can reach. |
| talk | "What does RWMutex buy you?" | Read the numbers in panel I. Its value depends on the hold time and the write share, so measure first. |
I run my tests with -race, and for each goroutine I can say what stops it.
0 of 12 known
Predict the output. The channel is closed before the first receive.
package main import "fmt" func main() { ch := make(chan int, 3) ch <- 1 ch <- 2 close(ch) fmt.Println(len(ch), cap(ch)) for range 3 { v, ok := <-ch fmt.Println(v, ok) } }Predict the output.
package main import "fmt" func main() { var ch chan int fmt.Println(len(ch), cap(ch)) ch <- 1 fmt.Println("sent") }Predict the output. The buffer has room.
package main import "fmt" func main() { ch := make(chan int, 1) close(ch) defer func() { fmt.Println("recovered:", recover()) v, ok := <-ch fmt.Println(v, ok) }() ch <- 1 fmt.Println("sent") }Predict the output.
package main import "fmt" func main() { ch := make(chan int) select { case ch <- 1: fmt.Println("sent") default: fmt.Println("no receiver") } buf := make(chan int, 1) select { case buf <- 1: fmt.Println("sent") default: fmt.Println("no room") } }Predict the output. Both channels hold a value.
package main import "fmt" func main() { a := make(chan string, 1) b := make(chan string, 1) a <- "a" b <- "b" select { case v := <-a: fmt.Println(v) case v := <-b: fmt.Println(v) } }Predict the output.
package main import "fmt" func main() { done := make(chan struct{}) close(done) var never chan int count := 0 for range 1000 { select { case <-never: fmt.Println("never") case <-done: count++ } } fmt.Println(count) }Predict the output.
package main import ( "context" "fmt" ) func main() { parent, cancelParent := context.WithCancel(context.Background()) child, cancelChild := context.WithCancel(parent) detached := context.WithoutCancel(parent) cancelChild() fmt.Println(parent.Err(), child.Err()) cancelParent() fmt.Println(parent.Err(), child.Err(), detached.Err()) }Predict the output.
package main import ( "context" "errors" "fmt" ) func main() { ctx, cancel := context.WithCancelCause(context.Background()) cancel(errors.New("disk full")) cancel(errors.New("second call")) fmt.Println(ctx.Err()) fmt.Println(context.Cause(ctx)) }Predict the output. The counter shows how often the function ran.
package main import ( "fmt" "sync" ) func main() { calls := 0 boom := func() int { calls++ panic("boom") } v := sync.OnceValue(boom) var once sync.Once do := func() { once.Do(func() { boom() }) } for range 2 { func() { defer func() { fmt.Println("OnceValue:", recover(), calls) }() v() }() } calls = 0 for range 2 { func() { defer func() { fmt.Println("Once:", recover(), calls) }() do() }() } }Predict the output. The timer fires long before the first print.
package main import ( "fmt" "time" ) func main() { t := time.NewTimer(time.Millisecond) time.Sleep(20 * time.Millisecond) fmt.Println(len(t.C), cap(t.C)) t.Reset(time.Hour) select { case <-t.C: fmt.Println("stale tick") default: fmt.Println("no tick") } }Predict the output. The goroutine waits for the write lock while main holds a read lock.
package main import ( "fmt" "sync" "time" ) func main() { var mu sync.RWMutex mu.RLock() go func() { mu.Lock() mu.Unlock() }() time.Sleep(10 * time.Millisecond) mu.RLock() fmt.Println("second read lock taken") }Predict the output.
package main import ( "fmt" "sync" ) func main() { defer func() { fmt.Println("recovered:", recover()) }() var mu sync.Mutex mu.Unlock() }
- atomic add
- 5.7 ns; 14.5 ns under contention.
- mutex
- 12.6 ns alone; 52.8 ns contended.
- channel
- 51.1 ns buffered; 221 ns unbuffered.
- goroutine
- 530 ns to start and finish; about 2.7 KB parked.
- Once
- 1.3 ns after the first call.
- ratio
- An unbuffered handoff costs about 4 times a contended mutex.
Go 1.27.3, 8-core Intel i9 laptop, GOMAXPROCS 16, median of 3 runs of 1 s, on a busy machine. Use these as orders of magnitude.