[Go] 使用读写锁对map资源进行安全处理

当需要有一个全局性的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:=0;i<10;i++{
        go func(i uint32){
            defer wg.Done()
            wg.Add(1)
            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{}
}

 

posted @ 2019-12-23 23:32  唯一客服系统开发笔记  阅读(710)  评论(0编辑  收藏  举报