Reviewer · Concurrency
Document and verify thread safety
Every type or function that may be shared across goroutines must state its concurrency contract in a doc comment: whether it is safe for concurrent use, what invariants its locks protect, and which methods require the caller to already hold a lock (e.g. "the caller of a method with the suffix Locked must hold the write lock"). If a method offers a different...
Every type or function that may be shared across goroutines must state its concurrency contract in a doc comment: whether it is safe for concurrent use, what invariants its locks protect, and which methods require the caller to already hold a lock (e.g. “the caller of a method with the suffix Locked must hold the write lock”). If a method offers a different consistency guarantee than a sibling method (e.g. not linearizable), say so explicitly.
Protect all shared mutable state with the simplest synchronization primitive that is correct. Prefer a single atomic.Int64/atomic.Bool over a mutex-guarded counter when only a counter is needed, and avoid clever tricks such as packing multiple flags into one integer with magic bit offsets purely to “save” a lock — the complexity cost usually outweighs the marginal performance gain (verify with a benchmark before choosing the complex form). Make resource-release functions idempotent (e.g. wrap unlock in a sync.Once) when a caller could plausibly invoke them twice.
Concurrency bugs are easy to hide in tests: when testing code that is meant to run safely across goroutines, give each goroutine distinct data (not the same shared input) so a race on shared internal buffers/state is actually exercised, and run these tests with -race (including in CI) so a shared-state bug fails loudly instead of passing silently. For example:
// Bad: all goroutines hash the same labels — a shared internal buffer
// won't be detected as a race.
for i := range mismatches {
go func() { h := newHasher(); h.HashSorted(sameLabels) }()
}
// Good: each goroutine hashes its own data, so a shared buffer fails
// under -race.
for i := range mismatches {
lbs := perGoroutineLabels[i]
go func() { h := newHasher(); h.HashSorted(lbs) }()
}
Finally, when a type is intentionally not safe for concurrent use (e.g. it owns unguarded mutable fields like cursor state or buffers), say so in its doc comment rather than leaving it to be discovered through a bug report.