douwudie8060
2016-12-02 11:39
浏览 61
已采纳

如何在Go中gc互斥锁映射?

I am making a cache wrapper around a database. To account for possibly slow database calls, I was thinking of a mutex per key (pseudo Go code):

mutexes = map[string]*sync.Mutex // instance variable

mutexes[key].Lock()
defer mutexes[key].Unlock()

if value, ok := cache.find(key); ok {
   return value
}
value = databaseCall(key)
cache.save(key, value)
return value

However I don't want my map to grow too much. My cache is an LRU and I want to have a fixed size for some other reasons not mentioned here. I would like to do something like

delete(mutexes, key)

when all the locks on the key are over but... that doesn't look thread safe to me... How should I do it?

Note: I found this question In Go, can we synchronize each key of a map using a lock per key? but no answer

图片转代码服务由CSDN问答提供 功能建议

我正在对数据库进行缓存包装。 为了解决可能很慢的数据库调用,我想到了每个键都有一个互斥锁(伪Go代码):

  mutexes = map [string] * sync.Mutex //实例变量 
 
mutexes [key] .Lock()
defermutex [key] .Unlock()
 
if值,好的:= cache.find(key); 好的{
返回值
} 
value = databaseCall(键)
cache.save(键,值)
返回值
   
 
 

但是我没有 希望我的地图增长太多。 我的缓存是LRU ,出于某些其他原因(此处未提及),我希望使用固定大小的缓存。 我想做类似的事情

 删除(互斥,键)
   
 
 

密钥已经结束,但是...对我来说似乎不是线程安全 ...我该怎么办?

注意:我发现了这个问题\ n 在 可以,我们可以使用每个按键的锁定来同步地图的每个按键吗?但没有答案

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doumaikuang4202 2018-04-18 08:43
    已采纳

    I wrote a simple similar implementation: mapmutex

    But instead of a map of mutexes, in this implementation, a mutex is used to guard the map and each item in the map is used like a 'lock'. The map itself is just simple ordinary map.

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题