Sync RWMutex Shared Map Access
Share a map across goroutines with sync.RWMutex: writers take the exclusive Lock while readers only take RLock and stay concurrent.
Code
package main
import (
"fmt"
"sync"
)
// Metrics 用 sync.RWMutex 保护共享(shared)map
type Metrics struct {
mu sync.RWMutex
counts map[string]int
}
func (m *Metrics) Add(key string, delta int) {
m.mu.Lock() // 写路径:独占访问
defer m.mu.Unlock()
m.counts[key] += delta
}
func (m *Metrics) Get(key string) int {
m.mu.RLock() // 读路径:多个读者可同时持有
defer m.mu.RUnlock()
return m.counts[key]
}
func main() {
metrics := Metrics{counts: make(map[string]int)}
var wg sync.WaitGroup
// 3 个写者各自累加
for _, delta := range []int{2, 5, 1} {
wg.Add(1)
go func(d int) {
defer wg.Done()
metrics.Add("hits", d)
}(delta)
}
// 与此同时 2 个读者并发读取,只拿 RLock
for i := 0; i < 2; i++ {
wg.Add(1)
go func() {
defer wg.Done()
_ = metrics.Get("hits")
}()
}
wg.Wait()
fmt.Println("hits =", metrics.Get("hits"))
fmt.Println("missing key reads as:", metrics.Get("none"))
}How the snippet works
Count the functions Add, Get and main as the entire surface area of Sync RWMutex Shared Map Access.
Repetition is confined to for _, delta := range []int{2, 5, 1} — the rest of the file is straight-line. A goroutine takes the work off the current one. defer schedules the cleanup, and the scheduled call fires no matter how the function exits.
Using it
Signature: func (m *Metrics) Add(key string, delta int)
Look for the hits =, missing key reads as: prefixes when the file runs; they tie each line to its step.
main is the driver: it invokes Add and Get before returning.
Key statements
metrics := Metrics{counts: make(map[string]int)}
func (m *Metrics) Add(key string, delta int) {
m.mu.Lock() // 写路径:独占访问
defer m.mu.Unlock()
m.counts[key] += delta
}
func (m *Metrics) Get(key string) int {
m.mu.RLock() // 读路径:多个读者可同时持有
defer m.mu.RUnlock()
return m.counts[key]
}
Interactive Tools for This Topic
FAQ
- What does Sync RWMutex Shared Map Access print when run?
- The script runs standalone; its 2 labeled outputs include `hits =`, `missing key reads as:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.