map并发安全问题
go语言官方博客中(Go maps in action)有说明:
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.
map类型不是并发安全的: 它没有定义当你同时读取和写入map时发生的情况,如果你需要在并发执行的goroutine中读取和写入map,那么访问时必须通过某种同步机制来调解。读写锁(sync.RWMutex)是用来保护map的一种常用方法。
因此,对于需要在并发执行的程序中使用map时,需要通过同步机制对map的访问进行控制。通常情况下会通过将Sync.RWMutex和map封装在一起,实现一个并发安全的结构。
package safemap
import "sync"
type SafeMap struct {
sync.RWMutex
mp map[interface{
}