当需要有一个全局性的map集合资源进行增删改数据时,需要对该map资源增加读写锁,防止并发时出现安全问题
下面的类就是举例 , 属性中的Conns模拟存储一些资源,对这些资源进行并发的增加数据,使用写锁锁住资源,当读取是使用读锁锁住资源
package snet import "sync" import errors type ConnManger struct { Conns map[uint32]string ConnLock sync.RWMutex } func NewConnManger() *ConnManger { cm := &ConnManger{ Conns: make(map[uint32]),} return cm } func (cm *ConnManger) Add(id uint32,value ) { cm.ConnLock.Lock() defer cm.ConnLock.Unlock() cm.Conns[id] = value } func (cm *ConnManger) Remove(id uint32) { cm.ConnLock.Lock() defer cm.ConnLock.Unlock() delete(cm.Conns,) } func (cm *ConnManger) Get(id uint32) (,error) { cm.ConnLock.RLock() defer cm.ConnLock.RUnlock() conn,ok := cm.Conns[] if !ok { return "",errors.New(connmanager get conn error ) } return conn,nil } func (cm *ConnManger) Len() int { return len(cm.Conns) } func (cm *ConnManger) Clean() { cm.ConnLock.Lock() defer cm.ConnLock.Unlock() for key,_ := range cm.Conns { delete(cm.Conns,key) } }
使用时
package main import single/snetlogstrconv func main() { cm:=snet.NewConnManger() var wg .WaitGroup for i:=0;i<10;i++{ go func(i uint32){ defer wg.Done() wg.Add(1) cm.Add(i,连接"+strconv.Itoa((i))) }(uint32(i)) } wg.Wait() log.Println(cm.Len()) range cm.Conns{ log.Println(key,value) } cm.Clean() log.Println(cm.Len()) select{} }