sync.Mutex and sync.RWMutex
Locking and read-write locking patterns
sync.Mutex and sync.RWMutex is a free Go Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Why mutexes?
When multiple goroutines share mutable state, concurrent reads and writes cause data races. A mutex serialises access so only one goroutine enters the critical section at a time.
sync.Mutex basics
Lock before reading/writing shared state; Unlock after. Use defer to guarantee unlocking even if the function panics.
var mu sync.Mutex
var counter int
func inc() {
mu.Lock()
defer mu.Unlock()
counter++
}Embedding Mutex in a struct
Embed the mutex in the struct it protects. By convention, the mutex is declared just above the fields it guards.
type SafeCounter struct {
mu sync.Mutex
v map[string]int
}
func (c *SafeCounter) Inc(key string) {
c.mu.Lock()
defer c.mu.Unlock()
c.v[key]++
}Do not copy a Mutex
A Mutex must not be copied after first use. Pass it by pointer or embed it in a struct passed by pointer. The go vet tool detects copies.
sync.RWMutex
sync.RWMutex allows multiple concurrent readers but only one writer. Use it when reads dominate and writes are rare to increase throughput.
var rw sync.RWMutex
var data map[string]int
func read(k string) int {
rw.RLock()
defer rw.RUnlock()
return data[k]
}
func write(k string, v int) {
rw.Lock()
defer rw.Unlock()
data[k] = v
}RLock vs Lock
RLock acquires a read lock (shared); Lock acquires a write lock (exclusive). A pending write lock blocks new read locks, preventing writer starvation.
TryLock (Go 1.18+)
mu.TryLock() acquires the lock only if it is currently unlocked, returning a boolean. Useful when blocking is unacceptable.
if mu.TryLock() {
defer mu.Unlock()
// critical section
}Deadlocks
Deadlock occurs when goroutine A holds lock 1 waiting for lock 2, and goroutine B holds lock 2 waiting for lock 1. Always acquire locks in the same order and keep critical sections short.
Lock granularity
A coarse lock is easier to reason about but reduces concurrency. Fine-grained locking improves throughput but increases complexity and deadlock risk. Start coarse and optimise if profiling shows contention.
Mutex vs channel
Use a mutex when protecting shared state with many readers/writers. Use a channel when transferring ownership of data between goroutines. Channels for communication, mutexes for synchronisation.
sync.Locker interface
sync.Locker is an interface with Lock and Unlock. Both Mutex and RWMutex implement it, allowing helper functions to accept either type.
Quick Check
When should you use sync.RWMutex instead of sync.Mutex?
Recap: Mutex and RWMutex
Key points:
- Mutex serialises access; always defer Unlock
- Never copy a Mutex after first use
- RWMutex: multiple readers OR one writer
- Acquire locks in consistent order to avoid deadlocks
Frequently asked questions
Is the “sync.Mutex and sync.RWMutex” lesson free?
Yes — the full text of “sync.Mutex and sync.RWMutex” is free to read here on the web, and the Go Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Go Academy course, upgrade to CoddyKit PRO.
What will I learn in “sync.Mutex and sync.RWMutex”?
Locking and read-write locking patterns You practise Go Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Go Academy?
No prior experience is required. Go Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “sync.Mutex and sync.RWMutex” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Go Academy lesson?
Yes. Every Go Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- sync.Mutex and sync.RWMutex
- sync.WaitGroup
- sync.Once and sync.Map
- Race Detector and Safe Patterns