前端之家收集整理的这篇文章主要介绍了
golang 1.8 并发安全Map简单实现,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
type SafeMap struct {
sync.RWMutex
Map map[int64]string
}
func NewSafeMap(size int) *SafeMap {
sm := new(SafeMap)
sm.Map = make(map[int64]string,size)
return sm
}
func (sm *SafeMap) ReadMap(key int64) string {
sm.RLock()
value := sm.Map[key]
sm.RUnlock()
return value
}
func (sm *SafeMap) WriteMap(key int64,value string) {
sm.Lock()
sm.Map[key] = value
sm.Unlock()
}
func (sm *SafeMap) Keys() []int64 {
sm.RLock()
value := make([]int64, 0)
for k,_ := range sm.Map {
value = append(value,k)
}
sm.RUnlock()
return value
}
原文链接:https://www.f2er.com/go/187311.html