go 最新版的 map 并发读是安全的吗。

5 天前
 YanSeven
只读不写,写的时候加锁,读的时候并发,这个安全吗。
3408 次点击
所在节点    Go 编程语言
24 条回复
YanSeven
5 天前
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
kfpenn
5 天前
并发读是安全的,但如果你读不加锁,不能保证读的时候没有写,如果读的时候遇到了写,就会 panic
xdeng
5 天前
标准库封装了个 sync.Map
Nanosk
5 天前
你发这个是旧的 map 吧,如果是 2 楼说的基本没问题,只有一点不太正确,并发读写并不是 panic ,而是 fatal
新的 SwissMap 没看过源码 不了解。
git00ll
5 天前
要用读写锁吧,不然可能读到不一致的数据
me262
5 天前
https://go.dev/blog/swisstable
别乱发啊 2 楼,最新都是 swiss table
ripperdev
5 天前
sync.Map 针对读多写少有优化,直接用就好了
oom
5 天前
不安全,读多写少加读写锁,或者使用原子 sync.Map ,但是取值相对麻烦
kfpenn
5 天前
@me262 所以呢?这个说明也没说最新的 map 支持并发啊
aladdinding
5 天前
我一般都是并发读,指针替换更新整个 map
ca2oh4
5 天前
sync.Map 太抽象了,连个类型都不给
ca2oh4
5 天前
@ripperdev sync.Map 太抽象了,连个类型都不给
charlie21
5 天前
有意思
ripperdev
5 天前
@ca2oh4 #12 什么意思?是指 Key 和 Value 都是 any 类型?
xxx88xxx
5 天前
我今天问了 GPT 类似的问题,GPT 告诉我最最优的方法是:并发前,将 map 深度拷贝后在使用
zoharSoul
5 天前
不是
Tidusy
5 天前
写和读同时触发会 fatal panic 的吧
bingfengfeifei
5 天前
写的时候加锁,加的是什么锁?那读的时候用锁吗?
1. 如果读的时候不用锁,仅仅写的时候用锁,那锁给谁的呢。 这不还可能在写的时候同时读吗。这种情况肯定是不行的。
2. 如果写的时候锁,读的时候也加读锁,这种是可以的,但是根据你的问法,好像并不是这种全加锁场景。
strobber16
4 天前
我还在等 sync/v2
ca2oh4
4 天前
@ripperdev 没错就是万恶的 any

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://ex.noerr.eu.org/t/1167771

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX