sync.Mutex and sync.RWMutex
- Version
- 1.27
- Review
- Draft
Summary#
A sync.Mutex lets one goroutine at a time use the data it guards. A sync.RWMutex allows either many readers or one writer.
Syntax#
For an exclusive lock, use Lock with either mutex type.
mu.Lock()
defer mu.Unlock()
For a shared read lock, use RLock with an RWMutex.
rw.RLock()
defer rw.RUnlock()
Example#
package main
import (
"fmt"
"sync"
)
type tally struct {
mu sync.RWMutex
counts map[string]int
}
func (t *tally) add(word string) {
t.mu.Lock()
defer t.mu.Unlock()
t.counts[word]++
}
func (t *tally) count(word string) int {
t.mu.RLock()
defer t.mu.RUnlock()
return t.counts[word]
}
func main() {
words := &tally{counts: map[string]int{}}
var group sync.WaitGroup
for range 100 {
group.Go(func() { words.add("go") })
}
group.Wait()
fmt.Println(words.count("go"))
}
Expected output#
100
Common mistakes#
A value receiver such as func (t tally) add copies the mutex, while the copied map field still refers to the same map. Each call then locks its own copy and protects nothing. Use pointer receivers and never copy a mutex after first use. Calling Lock again before Unlock blocks, and an RLock cannot be upgraded to a Lock.
Version applicability#
Both lock types date back to Go 1.0. The example requires Go 1.25 for WaitGroup.Go and uses integer range from Go 1.22.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0