-
Notifications
You must be signed in to change notification settings - Fork 0
/
singleflight.go
41 lines (34 loc) · 930 Bytes
/
singleflight.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package singleflight
import "sync"
// 正在进行中,或已经结束的请求
type call struct {
wg sync.WaitGroup
val interface{}
err error
}
// 管理不同 key 的请求(call)
type Group struct {
mu sync.Mutex // 保护 m 不被并发读写
m map[string]*call
}
func (g *Group) Do(key string, fn func() (interface{}, error)) (interface{}, error) {
g.mu.Lock()
if g.m == nil {
g.m = make(map[string]*call)
}
if c, ok := g.m[key]; ok {
g.mu.Unlock()
c.wg.Wait() // 如果请求正在进行中,则等待
return c.val, c.err // 请求结束,返回结果
}
c := new(call)
c.wg.Add(1) // 发起请求前加锁
g.m[key] = c // 添加到 g.m,表明 key 已经有对应的请求在处理
g.mu.Unlock()
c.val, c.err = fn() // 调用 fn,发起请求
c.wg.Done() // 请求结束
g.mu.Lock()
delete(g.m, key) // 更新 g.m
g.mu.Unlock()
return c.val, c.err // 返回结果
}