-
Notifications
You must be signed in to change notification settings - Fork 53
/
init.go
60 lines (53 loc) · 984 Bytes
/
init.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
package util
import (
"context"
"sync"
)
type Initializer struct {
setupCondOnce sync.Once
initCond *sync.Cond
initialized bool
}
func (i *Initializer) InitOnce(f func()) {
i.checkInitCond()
i.initCond.L.Lock()
defer i.initCond.L.Unlock()
if i.initialized {
return
}
f()
i.initialized = true
i.initCond.Broadcast()
}
func (i *Initializer) Initialized() bool {
i.checkInitCond()
i.initCond.L.Lock()
defer i.initCond.L.Unlock()
return i.initialized
}
func (i *Initializer) WaitForInit() {
i.checkInitCond()
i.initCond.L.Lock()
for !i.initialized {
i.initCond.Wait()
}
i.initCond.L.Unlock()
}
func (i *Initializer) WaitForInitContext(ctx context.Context) error {
done := make(chan struct{})
go func() {
defer close(done)
i.WaitForInit()
}()
select {
case <-done:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
func (i *Initializer) checkInitCond() {
i.setupCondOnce.Do(func() {
i.initCond = sync.NewCond(&sync.Mutex{})
})
}