1
SGL OP 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 |
2
kfpenn 9 小时 23 分钟前
并发读是安全的,但如果你读不加锁,不能保证读的时候没有写,如果读的时候遇到了写,就会 panic
|
![]() |
3
xdeng 9 小时 8 分钟前
标准库封装了个 sync.Map
|
4
Nanosk 9 小时 6 分钟前 ![]() 你发这个是旧的 map 吧,如果是 2 楼说的基本没问题,只有一点不太正确,并发读写并不是 panic ,而是 fatal
新的 SwissMap 没看过源码 不了解。 |
![]() |
5
git00ll 8 小时 40 分钟前
要用读写锁吧,不然可能读到不一致的数据
|
![]() |
6
me262 8 小时 7 分钟前 ![]() https://go.dev/blog/swisstable
别乱发啊 2 楼,最新都是 swiss table |
![]() |
7
ripperdev 8 小时 7 分钟前
sync.Map 针对读多写少有优化,直接用就好了
|
8
oom 4 小时 28 分钟前
不安全,读多写少加读写锁,或者使用原子 sync.Map ,但是取值相对麻烦
|
![]() |
10
aladdinding 3 小时 44 分钟前
我一般都是并发读,指针替换更新整个 map
|
11
ca2oh4 2 小时 13 分钟前
sync.Map 太抽象了,连个类型都不给
|
13
charlie21 2 小时 3 分钟前 via Android
有意思
|
15
xxx88xxx 1 小时 2 分钟前 via Android
我今天问了 GPT 类似的问题,GPT 告诉我最最优的方法是:并发前,将 map 深度拷贝后在使用
|