-
Notifications
You must be signed in to change notification settings - Fork 156
/
singleflight.go
72 lines (66 loc) · 1.06 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
package rueidis
import (
"context"
"sync"
"time"
)
type call struct {
ts time.Time
ch chan struct{}
cn int
mu sync.Mutex
}
func (c *call) Do(ctx context.Context, fn func() error) error {
c.mu.Lock()
c.cn++
ch := c.ch
if ch != nil {
c.mu.Unlock()
if ctxCh := ctx.Done(); ctxCh != nil {
select {
case <-ch:
case <-ctxCh:
return ctx.Err()
}
} else {
<-ch
}
return nil
}
ch = make(chan struct{})
c.ch = ch
c.mu.Unlock()
return c.do(ch, fn)
}
func (c *call) LazyDo(threshold time.Duration, fn func() error) {
c.mu.Lock()
ch := c.ch
if ch != nil {
c.mu.Unlock()
return
}
ch = make(chan struct{})
c.ch = ch
c.cn++
ts := c.ts
c.mu.Unlock()
go func(ts time.Time, ch chan struct{}, fn func() error) {
time.Sleep(time.Until(ts))
c.do(ch, fn)
}(ts.Add(threshold), ch, fn)
}
func (c *call) do(ch chan struct{}, fn func() error) (err error) {
err = fn()
c.mu.Lock()
c.ch = nil
c.cn = 0
c.ts = time.Now()
c.mu.Unlock()
close(ch)
return
}
func (c *call) suppressing() int {
c.mu.Lock()
defer c.mu.Unlock()
return c.cn
}