-
Notifications
You must be signed in to change notification settings - Fork 0
/
guard.go
55 lines (47 loc) · 922 Bytes
/
guard.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
package factory
import "sync"
// guard 防止并发
type guard struct {
locker sync.Mutex
callerMap map[string]*caller
}
func newGuard() *guard {
return &guard{
callerMap: make(map[string]*caller),
}
}
func (g *guard) run(key string, callback func() (interface{}, error)) (interface{}, error) {
g.locker.Lock()
c, ok := g.callerMap[key]
if ok {
g.locker.Unlock()
c.waiter.Wait()
return c.result()
} else {
c = newCall()
g.callerMap[key] = c
g.locker.Unlock()
}
c.run(callback)
g.locker.Lock()
delete(g.callerMap, key)
g.locker.Unlock()
return c.result()
}
type caller struct {
value interface{}
error error
waiter sync.WaitGroup
}
func newCall() *caller {
c := new(caller)
c.waiter.Add(1)
return c
}
func (c *caller) run(fn func() (interface{}, error)) {
c.value, c.error = fn()
c.waiter.Done()
}
func (c *caller) result() (interface{}, error) {
return c.value, c.error
}