-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsingleflight.go
46 lines (40 loc) · 890 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
42
43
44
45
46
package singleflight
import "sync"
type call struct {
wg sync.WaitGroup
val interface{}
err error
}
type Group struct {
// protects m
mu sync.Mutex
m map[string]*call
}
// key :request key in cache, fn : only call once and return no matter ho many time do
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)
}
// g.mu is protecting Group member m -> is map for every key
if c, ok := g.m[key]; ok {
g.mu.Unlock()
// if request processing then wait
c.wg.Wait()
return c.val, c.err
}
c := new(call)
// request and lock
c.wg.Add(1)
// mapping for key --> c, means already get request to process
g.m[key] = c
g.mu.Unlock()
// assign to call obj, call fn
c.val, c.err = fn()
c.wg.Done()
// lock
g.mu.Lock()
delete(g.m, key)
g.mu.Unlock()
return c.val, c.err
}