Psyduck
Psyduck copied to clipboard
go-map
trafficstars
go-map 中可以加入并发访问时导致panic的情况
今天早上又翻了一遍 mapassign_faststr(),mapaccess1_faststr() 和 mapaccess2_faststr() 这几个函数的实现,对于是否存在并发访问的处理还是比较简单的,大概率不会在 XMind 里面补充了 😸 。
// 写 map
func mapassign_faststr(t *maptype, h *hmap, s string) unsafe.Pointer {
// other codes ......
// 判断当前是否有其它 Goroutine 正在写 hmap
if h.flags&hashWriting != 0 {
throw("concurrent map writes")
}
// other codes ......
// Set hashWriting after calling t.hasher for consistency with mapassign.
// 设置标志位
h.flags ^= hashWriting
// other codes ......
// 如果此时 flags 中不包含 hashWriting 的话,那么必然并发写的问题
if h.flags&hashWriting == 0 {
throw("concurrent map writes")
}
// 恢复标志位
h.flags &^= hashWriting
}
// value := map[key] 形式的读 map
func mapaccess1_faststr(t *maptype, h *hmap, ky string) unsafe.Pointer {
// other codes ......
// 判断是否有其它 Goroutine 正在写 map
if h.flags&hashWriting != 0 {
throw("concurrent map read and map write")
}
// other codes ......
}
因为 hashmap 本身就并不是并发安全的,所以这块儿的代码处理也比较简单,感觉就是起一个提示的作用。