...
Source file src/internal/singleflight/singleflight.go
1
2
3
4
5
6
7 package singleflight
8
9 import "sync"
10
11
12 type call struct {
13 wg sync.WaitGroup
14
15
16
17 val interface{}
18 err error
19
20
21
22
23 dups int
24 chans []chan<- Result
25 }
26
27
28
29 type Group struct {
30 mu sync.Mutex
31 m map[string]*call
32 }
33
34
35
36 type Result struct {
37 Val interface{}
38 Err error
39 Shared bool
40 }
41
42
43
44
45
46
47 func (g *Group) Do(key string, fn func() (interface{}, error)) (v interface{}, err error, shared bool) {
48 g.mu.Lock()
49 if g.m == nil {
50 g.m = make(map[string]*call)
51 }
52 if c, ok := g.m[key]; ok {
53 c.dups++
54 g.mu.Unlock()
55 c.wg.Wait()
56 return c.val, c.err, true
57 }
58 c := new(call)
59 c.wg.Add(1)
60 g.m[key] = c
61 g.mu.Unlock()
62
63 g.doCall(c, key, fn)
64 return c.val, c.err, c.dups > 0
65 }
66
67
68
69
70
71 func (g *Group) DoChan(key string, fn func() (interface{}, error)) (<-chan Result, bool) {
72 ch := make(chan Result, 1)
73 g.mu.Lock()
74 if g.m == nil {
75 g.m = make(map[string]*call)
76 }
77 if c, ok := g.m[key]; ok {
78 c.dups++
79 c.chans = append(c.chans, ch)
80 g.mu.Unlock()
81 return ch, false
82 }
83 c := &call{chans: []chan<- Result{ch}}
84 c.wg.Add(1)
85 g.m[key] = c
86 g.mu.Unlock()
87
88 go g.doCall(c, key, fn)
89
90 return ch, true
91 }
92
93
94 func (g *Group) doCall(c *call, key string, fn func() (interface{}, error)) {
95 c.val, c.err = fn()
96 c.wg.Done()
97
98 g.mu.Lock()
99 delete(g.m, key)
100 for _, ch := range c.chans {
101 ch <- Result{c.val, c.err, c.dups > 0}
102 }
103 g.mu.Unlock()
104 }
105
106
107
108
109
110
111 func (g *Group) ForgetUnshared(key string) bool {
112 g.mu.Lock()
113 defer g.mu.Unlock()
114 c, ok := g.m[key]
115 if !ok {
116 return true
117 }
118 if c.dups == 0 {
119 delete(g.m, key)
120 return true
121 }
122 return false
123 }
124
View as plain text