只锁定一个条目并不容易,但是您想要更高效,Go 中的一个好做法是使用通道与顺序进程进行通信。这样,就没有共享变量和锁了。
一个简单的例子:
type request struct {
reqtype string
key string
val interface{}
response chan<- result
}
type result struct {
value interface{}
err error
}
type Cache struct{ requests chan request }
func New() *Cache {
cache := &Cache{requests: make(chan request)}
go cache.server()
return cache
}
func (c *Cache) Get(key string) (interface{}, error) {
response := make(chan result)
c.requests <- request{key, response}
res := <-response
return res.value, res.err
}
func (c *Cache) Set(key, val string) {
c.requests <- request{"SET", key, val, response}
}
func (c *Cache) server() {
cache := make(map[string]interface{})
for req := range memo.requests {
switch req.reqtype {
case "SET":
cache[req.key] = req.val
case "GET":
e := cache[req.key]
if e == nil {
req.response <- result{e, errors.New("not exist")}
} else {
req.response <- result{e, nil}
}
}
}
}