go-utils/common/sync_map.go

50 lines
950 B
Go
Raw Normal View History

2017-12-22 09:44:04 +00:00
package common
import (
"sync"
)
//安全的Map
type SynchronizedMap struct {
rw *sync.RWMutex
data map[interface{}]interface{}
}
//存储操作
func (sm *SynchronizedMap) Put(k, v interface{}) {
sm.rw.Lock()
defer sm.rw.Unlock()
sm.data[k] = v
}
//获取操作
func (sm *SynchronizedMap) Get(k interface{}) interface{} {
sm.rw.RLock()
defer sm.rw.RUnlock()
return sm.data[k]
}
//删除操作
func (sm *SynchronizedMap) Delete(k interface{}) {
sm.rw.Lock()
defer sm.rw.Unlock()
delete(sm.data, k)
}
//遍历Map并且把遍历的值给回调函数可以让调用者控制做任何事情
func (sm *SynchronizedMap) Each(cb func(interface{}, interface{})) {
sm.rw.RLock()
defer sm.rw.RUnlock()
for k, v := range sm.data {
cb(k, v)
}
}
//生成初始化一个SynchronizedMap
func NewSynchronizedMap() *SynchronizedMap {
return &SynchronizedMap{
rw: new(sync.RWMutex),
data: make(map[interface{}]interface{}),
}
}