前端之家收集整理的这篇文章主要介绍了
Golang 并发非阻塞缓存,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
《The Go Programming Language》笔记
import "sync"
type Func func(key string) (interface{},error)
type result struct {
value interface{}
err error
}
type entry struct {
res result
ready chan struct{}
}
type MemoryCache struct {
f Func
mu sync.Mutex
cache map[string]*entry
}
func New(f Func) *MemoryCache {
return &MemoryCache{f: f,cache: make(map[string]*entry)}
}
func (mc *MemoryCache) Get(key string) (interface{},error) {
mc.mu.Lock()
e := mc.cache[key]
if e == nil {
e = &entry{ready:make(chan struct{})}
mc.cache[key] = e
mc.mu.Unlock()
e.res.value,e.res.err = mc.f(key)
close(e.ready)
}else {
mc.mu.Unlock()
<-e.ready
}
return e.res.value,e.res.err
}
type Func func(key string) (interface{},error)
type result struct {
value interface{}
err error
}
type entry struct {
res result
ready chan struct{}
}
type request struct {
key string
response chan<- result
}
type MemoryCache struct {
requests chan request
}
func New(f Func) *MemoryCache {
mc := &MemoryCache{requests: make(chan request)}
go mc.server(f)
return mc
}
func (mc *MemoryCache) Get(key string) (interface{},error) {
response := make(chan result)
mc.requests <- request{key,response}
res := <- response
return res.value,res.err
}
func (mc *MemoryCache) server(f Func) {
cache := make(map[string]*entry)
for req := range mc.requests {
e := cache[req.key]
if e == nil {
e = &entry{ready: make(chan struct{})}
cache[req.key] = e
go e.call(f,req.key)
}
go e.deliver(req.response)
}
}
func (mc *MemoryCache) Close() {
close(mc.requests)
}
func (e *entry) call(f Func,key string) {
e.res.value,e.res.err = f(key)
close(e.ready)
}
func (e *entry) deliver(response chan<- result) {
<-e.ready
response <- e.res
}
原文链接:https://www.f2er.com/go/189146.html