最近工程上有段代码panic了,发现又是犯了map并发写的问题。自己来回顾一下这个问题,避免自己也犯错
go map写入的源码在这里其中有一段throw exception和写入标志位的逻辑
if h.flags&hashWriting != 0 {
throw("concurrent map writes")
}
hash := t.hasher(key, uintptr(h.hash0))
// Set hashWriting after calling t.hasher, since t.hasher may panic,
// in which case we have not actually done a write.
h.flags ^= hashWriting
这里的标志位含义也在同文件,即表示有goroutinue在写这个map
// flags
iterator = 1 // there may be an iterator using buckets
oldIterator = 2 // there may be an iterator using oldbuckets
hashWriting = 4 // a goroutine is writing to the map
sameSizeGrow = 8 // the current map growth is to a new map of the same size
因此如果并发写入就会panic
golang在设计时候并没有对map进行写并发控制,理由在go的