Go Reference ยท Concurrency and Context
Go sync.Mutex and sync.RWMutex types
Reference for Go sync.Mutex and sync.RWMutex: Lock, Unlock, TryLock, RLock, the defer pattern, struct embedding, deadlocks and when to prefer atomics.
A sync.Mutex is a mutual exclusion lock. At most one goroutine can hold it at a time; others calling Lock wait until it is released. Placing the code that touches shared data between Lock and Unlock guarantees only one goroutine runs it at once, and it also makes the changes made inside visible to the next goroutine that takes the lock.
A sync.RWMutex is a reader/writer lock. Any number of goroutines can hold the read lock (RLock) together, but the write lock (Lock) is exclusive. It pays off when reads are much more frequent than writes and take a noticeable time.
var mu sync.Mutex mu.Lock() defer mu.Unlock()
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Syntax
type Mutex struct{ /* ... */ } func (m *Mutex) Lock() func (m *Mutex) Unlock() func (m *Mutex) TryLock() bool type RWMutex struct{ /* ... */ } func (rw *RWMutex) Lock() func (rw *RWMutex) Unlock() func (rw *RWMutex) RLock() func (rw *RWMutex) RUnlock() func (rw *RWMutex) TryLock() bool func (rw *RWMutex) TryRLock() bool func (rw *RWMutex) RLocker() Locker
| Method | Description |
|---|---|
Lock |
Acquire the exclusive lock, blocking until it is available. |
Unlock |
Release it. |
TryLock |
Acquire only if free right now; returns true on success. Added in Go 1.18. |
RLock, RUnlock |
Acquire and release a shared read lock. |
TryRLock |
Non-blocking read lock attempt (Go 1.18). |
Panics and fatal errors: unlocking an unlocked mutex is a fatal error ("sync: unlock of unlocked mutex") that cannot be recovered. The zero value of both types is an unlocked mutex ready for use.
Usage notes
- Use
defer mu.Unlock()right afterLockso every return path, including panics, releases the lock. - A mutex is not reentrant. Locking it again in the same goroutine deadlocks. Split your code into an exported method that locks and an unexported helper that assumes the lock is held.
- Do not copy a mutex. Methods on structs that contain one must use pointer receivers, or the copy gets its own lock.
go vetwarns about it. - Writers wait for readers, and once a writer is waiting, new
RLockcalls block until it is done. So a goroutine must not takeRLocktwice nested: if a writer arrives between the two calls, both goroutines deadlock. - No upgrade: you cannot go from a read lock to a write lock. Release, then lock for writing, and re-check the condition.
RWMutexis not always faster. It has more overhead thanMutex; use it only when reads dominate and the protected section is not tiny. Measure with a benchmark.- Lock ordering: if code needs two locks, always take them in the same order everywhere.
- Alternatives: for a single integer,
sync/atomicis lighter; for a map with stable keys, seesync.Map; for ownership transfer, use channels. TryLockis rarely right. Code that needs it often has a design problem; the documentation itself calls its correct uses rare.
Related
sync,sync.WaitGroup,sync.Map,sync/atomic,defer- Lessons: The sync package, Data races