-
Notifications
You must be signed in to change notification settings - Fork 1
/
singleflight.go
74 lines (62 loc) · 1.28 KB
/
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package syncx
import "sync"
type SingleFlight interface {
Do(key string, fn func() (interface{}, error)) (interface{}, error)
DoEx(key string, fn func() (interface{}, error)) (interface{}, bool, error)
}
type _FlightGroup struct {
calls map[string]*_Call
lock sync.Mutex
}
type _Call struct {
wg sync.WaitGroup
val interface{}
err error
}
func NewSingleFlight() SingleFlight {
return &_FlightGroup{
calls: make(map[string]*_Call),
}
}
func (g *_FlightGroup) Do(key string, fn func() (interface{}, error)) (interface{}, error) {
var (
c *_Call
ok bool
)
g.lock.Lock()
if c, ok = g.calls[key]; ok {
g.lock.Unlock()
c.wg.Wait()
return c.val, c.err
}
c = g.MakeCall(key, fn)
return c.val, c.err
}
func (g *_FlightGroup) DoEx(key string, fn func() (interface{}, error)) (interface{}, bool, error) {
var (
c *_Call
ok bool
)
g.lock.Lock()
if c, ok = g.calls[key]; ok {
g.lock.Unlock()
c.wg.Wait()
return c.val, false, c.err
}
c = g.MakeCall(key, fn)
return c.val, true, c.err
}
func (g *_FlightGroup) MakeCall(key string, fn func() (interface{}, error)) *_Call {
c := new(_Call)
c.wg.Add(1)
g.calls[key] = c
g.lock.Unlock()
defer func() {
g.lock.Lock()
delete(g.calls, key)
g.lock.Unlock()
c.wg.Done()
}()
c.val, c.err = fn()
return c
}