Maps are not safe for concurrent use: it’s not defined what happens when you read and write to them simultaneously. If you need to read from and write to a map from concurrently executing goroutines, the accesses must be mediated by some kind of synchronization mechanism. One common way to protect maps is with sync.RWMutex.
映射结构不适用于并发场景:当同时进行读写操作时,其行为是未定义的。若需要在并发执行的 goroutine 中对映射进行读写操作,必须通过某种同步机制来协调访问。保护映射的常用方式之一是使用 sync.RWMutex 。
This statement declares a counter variable that is an anonymous struct containing a map and an embedded sync.RWMutex.
该语句声明了一个 counter 变量,这是一个包含映射和嵌入式 sync.RWMutex 的匿名结构体。
var counter = struct{
sync.RWMutex
m map[string]int
}{m: make(map[string]int)}
To read from the counter, take the read lock:
读取计数器时需获取读锁:
counter.RLock()
n := counter.m["some_key"]
counter.RUnlock()
fmt.Println("some_key:", n)
To write to the counter, take the write lock:
写入计数器时需获取写锁:
counter.Lock()
counter.m["some_key"]++
counter.Unlock()
来源:
https://go.dev/blog/maps?utm_source=chatgpt.com