当需要有一个全局性的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]string),
}
return cm
}
func (cm *ConnManger) Add(id uint32, value string) {
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, id)
}
func (cm *ConnManger) Get(id uint32) (string, error) {
cm.ConnLock.RLock()
defer cm.ConnLock.RUnlock()
conn, ok := cm.Conns[id]
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/snet" import "log" import "sync" import "strconv"
func main() {
cm:=snet.NewConnManger()
var wg sync.WaitGroup
for i:=;i<;i++{
go func(i uint32){
defer wg.Done()
wg.Add()
cm.Add(i,"连接"+strconv.Itoa(int(i)))
}(uint32(i))
}
wg.Wait()
log.Println(cm.Len())
for key,value:=range cm.Conns{
log.Println(key,value)
}
cm.Clean()
log.Println(cm.Len())
select{}
}