Sync Mutex Basics
Fast recall
Quick revision
Core answer
Whether you understand Sync Mutex Basics beyond memorized syntax.
Giving a definition without explaining a practical trade-off.
Connect the concept to a small production example and state its complexity or failure mode.
Interview-ready guide
Interview answer
A mutex guarantees exactly one goroutine in the critical section:
var (
counter int
mu sync.Mutex
)
func increment() {
mu.Lock()
counter++
mu.Unlock()
}
// 100 goroutines → counter exactly 100 (verified with mutex)
// 100 goroutines without → ~90 (verified — lost updates)Without the mutex: counter++ is three operations (read, add, write); goroutines interleave and updates vanish. With: exactly 100, every time.
The rules: defer mu.Unlock() right after Lock (runs on every exit path); var mu sync.Mutex is ready (zero-value, no constructor); don't copy a mutex (go vet's copylocks catches it).
The mistake to name: incrementing without the lock because it's just one line — one line is three operations, and the update vanishes silently.
Sync Mutex Basics
Direct Answer
A mutual-exclusion lock. Lock() blocks until acquired, Unlock() releases. Use when goroutines read AND write shared state — the lock serializes access so only one goroutine is in the critical section.
Deep Dive & Architecture
The race mechanism: counter++ compiles to load, add, store. Two goroutines can both load 5, both compute 6, both store 6 — two increments, one result. Multiply by 100 goroutines, ~10 overlaps: 90 (verified). The mutex serializes: Lock CASes the state to held (atomic); the critical section runs alone; Unlock wakes the FIFO queue's head. An uncontended Lock is one atomic instruction — nanoseconds.
The critical-section discipline: the section contains exactly the shared-state access, nothing slow (no I/O, no allocations inside — everything inside is serialized). The read-copy-update pattern for slow work: copy under the lock, release, work on the copy.
The copylocks vet check: a struct containing a Mutex passed by value copies the lock state — two goroutines 'holding' the same logical lock. The idioms: methods on the struct (pointer receiver), or embed sync.Mutex.
Common Mistakes & Pitfalls
Giving a definition without explaining a practical trade-off.
Check your understanding
Answer these without looking back at the article.
- When would you use Sync Mutex Basics in a real project?
- How would you compare Sync Mutex Basics with an alternative?
- What is a common mistake when using Sync Mutex Basics?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.