go中map并发使用是不安全的,当你使用goroutine同时对一个map进行读写操作时,不确定会发生什么(由于读写执行顺序不确定造成的).针对这种情况,我们要添加读写锁对sync.RWMutex
其进行同步.
var counter = struct{ sync.RWMutex m map[string]int}{m: make(map[string]int)}从counter读取数据,使用读锁
counter.RLock()n := counter.m["some_key"]counter.RUnlock()fmt.Println("some_key:", n)向counter写数据,使用写锁
counter.Lock()counter.m["some_key"]++counter.Unlock()参考: