golang 中map并发读写

亡梦爱人 提交于 2019-12-04 23:53:58

项目上之前出现map并发问题,查找资料后自己整理一下。

代码如下:

//map 并发存取
type BeeMap struct {
    lock *sync.RWMutex
    bm   map[string]interface{}
}

func NewBeeMap() *BeeMap {
    return &BeeMap{
        lock: new(sync.RWMutex),
        bm:   make(map[string]interface{}),
    }
}

//Get from maps return the k's value
func (m *BeeMap) Get(k string) interface{} {
    m.lock.RLock()
    defer m.lock.RUnlock()
    if val, ok := m.bm[k]; ok {
        return val
    }
    return nil
}

// Maps the given key and value. Returns false
// if the key is already in the map and changes nothing.
func (m *BeeMap) Set(k string, v interface{}) bool {
    m.lock.Lock()
    defer m.lock.Unlock()
    if val, ok := m.bm[k]; !ok {
        m.bm[k] = v
    } else if val != v {
        m.bm[k] = v
    } else {
        return false
    }
    return true
}

// Returns true if k is exist in the map.
func (m *BeeMap) Check(k string) bool {
    m.lock.RLock()
    defer m.lock.RUnlock()
    if _, ok := m.bm[k]; !ok {
        return false
    }
    return true
}

func (m *BeeMap) Delete(k string) {
    m.lock.Lock()
    defer m.lock.Unlock()
    delete(m.bm, k)
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!