sync.Mutex vs sync.RWMutex
sync.Mutex vs sync.RWMutex
When working with concurrent programs in Go, controlling access to shared data is crucial. That’s where sync.Mutex and sync.RWMutex come in.
- sync.Mutex
A Mutex (short for mutual exclusion lock) is the simplest locking mechanism.
It allows only one goroutine to access a resource at a time.
If one goroutine has locked the mutex, all others trying to lock it will block until it’s unlocked.
Usage:
Lock(): acquire exclusive access
Unlock(): release the lock
When to use:
- When modifying (writing) shared data.
- Only one goroutine can hold the lock at a time.
- Blocks all readers and writers.
- sync.RWMutex
An RWMutex (read–write mutex) allows multiple readers at the same time — but only one writer, and writers block readers.
Usage:
RLock(): acquire shared access for reading
RUnlock(): release shared read lock
Lock() / Unlock(): exclusive access for writing
When to use:
- Use RLock() when reading shared data.
- Multiple readers can hold it simultaneously.
- Writers are blocked until all readers release their locks.