合规国际互联网加速 OSASE为企业客户提供高速稳定SD-WAN国际加速解决方案。 广告
### 安全map ```go package main import ( "fmt" "sync" ) // NewSafeMap 初始化SafeMap func NewSafeMap() *SafeMap { return &SafeMap{ Data: map[string]interface{}{}, } } // SafeMap 安全Map type SafeMap struct { Data map[string]interface{} // 自定义map Lock sync.RWMutex } // Load Get方法 func (c *SafeMap) Load(k string) interface{} { c.Lock.RLock() defer c.Lock.RUnlock() if v, exit := c.Data[k]; exit { return v } return nil } // Store Set方法 func (c *SafeMap) Store(k string, v interface{}) { c.Lock.Lock() defer c.Lock.Unlock() if c.Data == nil { c.Data = make(map[string]interface{}) } c.Data[k] = v } func main() { m := SafeMap{ Data: make(map[string]interface{}), } var wg sync.WaitGroup loopCount := 10 wg.Add(loopCount) for i := 0; i < loopCount; i++ { num := i go func() { m.Store(fmt.Sprintf("%d", num), num+1) wg.Done() }() } wg.Wait() m.Data["3"] = 18 fmt.Println(m.Data) } ```