By Abhijith N M · Reviewed 24 October 2026 · Editorial standards
The Go proverb says to share memory by communicating, but that is guidance, not a prohibition. A cache, a counter and a connection pool all share state, and a sync.Mutex is the right tool when the state is a data structure rather than a stream of work. The mutex zero value is ready to use; copying a mutex after use is a bug.
Keep critical sections short: lock, read or write the fields, unlock. Do not call a function that might block while holding a lock, and do not hold two locks in different orders in different code paths — that is a deadlock recipe. sync.RWMutex helps only when reads dominate and the read critical section does real work; it is not automatically faster.
For a single counter, sync/atomic is cheaper than a mutex and expresses the intent precisely. atomic.Int64 wraps the operations as methods (Add, Load, Store), which is harder to misuse than the old functions. Atomic operations do not make a group of fields consistent with each other — for that, use a mutex.
A context.Context travels with a request and tells every layer when the request is over. Pass it as the first parameter, name it ctx, and never store it in a struct. context.WithCancel, WithTimeout and WithDeadline derive children; the derived context's Done channel closes and Err() explains why. Always defer cancel() to release the timer or parent registration. Cancellation is cooperative: your loop must check ctx.Done().
package main
import (
"context"
"fmt"
"sync"
"sync/atomic"
)
func main() {
var mu sync.Mutex
total := 0
var wg sync.WaitGroup
for i := 0; i < 100; i++ {
wg.Add(1)
go func() {
defer wg.Done()
mu.Lock()
defer mu.Unlock()
total++
}()
}
wg.Wait()
var atomicTotal atomic.Int64
for i := 0; i < 100; i++ {
wg.Add(1)
go func() {
defer wg.Done()
atomicTotal.Add(1)
}()
}
wg.Wait()
fmt.Println("mutex", total, "atomic", atomicTotal.Load())
var once sync.Once
for i := 0; i < 3; i++ {
once.Do(func() { fmt.Println("init once") })
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
started := make(chan struct{})
stopped := make(chan struct{})
go func() {
close(started)
<-ctx.Done()
close(stopped)
}()
<-started
cancel()
<-stopped
fmt.Println("context cancelled:", ctx.Err())
}| Primitive | Protects | Reach for it when |
|---|---|---|
sync.Mutex | A group of fields | State is a structure mutated by many goroutines |
sync.RWMutex | Read-heavy fields | Reads dominate and are not trivial |
sync/atomic | One scalar | A single counter or flag |
sync.Once | One-time initialization | Expensive setup that must run once |
context.Context | Cancellation and deadlines | Work crosses layers or a request boundary |
| Channels | Ownership of values | Passing work between goroutines |
Key takeaways
Use a mutex for shared structures and sync/atomic for single counters; keep critical sections short.
Never copy a mutex or a WaitGroup after first use; go vet catches it.
context.Context carries cancellation and deadlines, as the first parameter, never in a struct.
Always defer cancel() for derived contexts, and check ctx.Done() in long-running loops.
Cancellation is cooperative: the receiver decides when to stop.
Written and edited by the nexGenCoders team. Spotted a mistake? Tell us and we will fix it.
Don't lose this lesson
Create a free account to save your progress, keep your streak, and work toward a shareable certificate.