golang中的map在并发下是不安全的,如果同时读写会出现:
type M struct { Map map[string]string}// Set ...func (m *M) Set(key, value string) { m.Map[key] = value}// Get ...func (m *M) Get(key string) string { return m.Map[key]}func main() { c := M{Map: make(map[string]string)} wg := sync.WaitGroup{} for i := 0; i < 21; i++ { wg.Add(1) go func(n int) { k, v := strconv.Itoa(n), strconv.Itoa(n) c.Set(k, v) log.Printf("k=:%v,v:=%v\n", k, c.Get(k)) wg.Done() }(i) } wg.Wait()}
concurrent map read and map write
同时多个协程读取不会出现问题,为了解决此问题,可以在写的时候加锁,让写map时候,读只能同步等待
最常用的加锁方式是在读写时加上:sync.Mutex互斥锁
func (m *M) Set(key, value string) { m1.Lock() m.Map[key] = value m1.Unlock()}
互斥锁是由操作系统实现,时间复杂度高,系统实现sync.Map进行并发
ar m sync.Map // 1. 写入 m.Store("qcrao", 18) m.Store("stefno", 20) // 2. 读取 age, _ := m.Load("qcrao") fmt.Println(age.(int))
使用 sync.map 之后,对 map 的读写,不需要加锁。并且它通过空间换时间的方式,使用 read 和 dirty 两个 map 来进行读写分离,降低锁时间来提高效率
文章来源:智云一二三科技
文章标题:【golang】小技巧-sync.Map解决map并发不安全问题
文章地址:https://www.zhihuclub.com/286.shtml