go手动添加锁=安全
package main import ( "fmt" "sync" "time" ) // 为了解决线程不安全,我们自己加锁 type concurentMat struct { mp map[int]int sync.RWMutex } // 通过set方法做原有map的赋值 func (c *concurentMat)Set(key, v int) { // 添加写锁 c.Lock() c.mp[key] = v c.Unlock() } // 通过get方法做原有map的读取值 func (c *concurentMat)Get(key int) int{ c.RLock() r := c.mp[key] c.RUnlock() return r } func main(){ c := concurentMat{ mp: make(map[int]int), } // 并发一个线程循环写 go func() { for i:= 0; i< 1000; i++ { c.Set(i, i) } }() go func() { for i:= 0; i< 1000; i++ { ret := c.Get(i) fmt.Println(i, ret) } }() time.Sleep(1 * time.Second) }