【发布时间】:2016-06-27 17:13:15
【问题描述】:
我一直在阅读有关 goroutines 和同步包的信息,我的问题是……在读取不同 goroutine 上的数据时,我是否总是需要锁定解锁?
例如,我的服务器上有一个变量
config := make(map[string]string)
然后在不同的 goroutines 上我想从 config 中读取。不使用同步阅读是否安全?
我猜写作需要使用同步包来完成。但我不确定是否阅读
例如我有一个简单的内存缓存系统
type Cache interface {
Get(key string) interface{}
Put(key string, expires int64, value interface{})
}
// MemoryCache represents a memory type of cache
type MemoryCache struct {
c map[string]*MemoryCacheValue
rw sync.RWMutex
}
// MemoryCacheValue represents a memory cache value
type MemoryCacheValue struct {
value interface{}
expires int64
}
// NewMemoryCache creates a new memory cache
func NewMemoryCache() Cache {
return &MemoryCache{
c: make(map[string]*MemoryCacheValue),
}
}
// Get stores something into the cache
func (m *MemoryCache) Get(key string) interface{} {
if v, ok := m.c[key]; ok {
return v
}
return nil
}
// Put retrieves something from the cache
func (m *MemoryCache) Put(key string, expires int64, value interface{}) {
m.rw.Lock()
m.c[key] = &MemoryCacheValue{
value,
time.Now().Unix() + expires,
}
m.rw.Unlock()
}
我在这里是安全的,还是我只想阅读时仍需要锁定解锁?
【问题讨论】:
标签: go synchronization