Skip to content

Commit

Permalink
解读防止缓存击穿代码学习
Browse files Browse the repository at this point in the history
  • Loading branch information
[email protected] committed May 25, 2020
1 parent 96682b1 commit cdffce3
Showing 1 changed file with 6 additions and 0 deletions.
6 changes: 6 additions & 0 deletions singleflight/singleflight.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ package singleflight
import "sync"

// call is an in-flight or completed Do call
// 包装一个key获取值锁需要的一些参数
type call struct {
wg sync.WaitGroup
val interface{}
Expand All @@ -43,19 +44,24 @@ func (g *Group) Do(key string, fn func() (interface{}, error)) (interface{}, err
if g.m == nil {
g.m = make(map[string]*call)
}

if c, ok := g.m[key]; ok {
// 已经有协程在处理了,阻塞(c.wg.Wait())等待完成
g.mu.Unlock()
c.wg.Wait()
return c.val, c.err
}
// 目前没有协程在处理,新建一个处理的任务
c := new(call)
c.wg.Add(1)
g.m[key] = c
g.mu.Unlock()

// 执行获取key的函数,并将结果赋值给这个Call
c.val, c.err = fn()
c.wg.Done()

// 重新上锁删除key
g.mu.Lock()
delete(g.m, key)
g.mu.Unlock()
Expand Down

0 comments on commit cdffce3

Please sign in to comment.