/
syncer.go
142 lines (117 loc) · 2.49 KB
/
syncer.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
package util
import (
"context"
"os"
"os/signal"
"sync"
"syscall"
)
type SyncerWaitMode int
const (
SyncerWaitModeCancel = 1
SyncerWaitModeIdle = 2
SyncerWaitModeAny = 3
)
type Syncer struct {
parent *Syncer
ctxs context.CancelFunc
wg *sync.WaitGroup
ctx context.Context
ctxc context.CancelFunc
once *sync.Once
onced chan bool
}
func newSyncer(ctx context.Context, parent *Syncer, ctxs context.CancelFunc) *Syncer {
syncer := &Syncer{
parent: parent,
ctxs: ctxs,
}
syncer.wg = &sync.WaitGroup{}
syncer.ctx, syncer.ctxc = context.WithCancel(ctx)
syncer.once = &sync.Once{}
syncer.onced = make(chan bool, 1)
return syncer
}
func (syncer *Syncer) increase() {
if syncer.parent != nil {
syncer.parent.increase()
}
syncer.wg.Add(1)
}
func (syncer *Syncer) decrease() {
if syncer.parent != nil {
syncer.parent.decrease()
}
syncer.once.Do(func() { syncer.onced <- true })
syncer.wg.Done()
}
func CreateSyncerWithSig(ctx context.Context) *Syncer {
sigs := []os.Signal{syscall.SIGHUP, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGILL, syscall.SIGTERM}
ctx, ctxs := signal.NotifyContext(ctx, sigs...)
return newSyncer(ctx, nil, ctxs)
}
func CreateSyncer(ctx context.Context) *Syncer {
return newSyncer(ctx, nil, nil)
}
func CreateSyncerGroup(ctx context.Context, syncers ...**Syncer) {
for _, syncer := range syncers {
*syncer = newSyncer(ctx, nil, nil)
}
}
func WaitReleaseSyncerGroup(act SyncerWaitMode, syncers ...*Syncer) {
for _, syncer := range syncers {
syncer.WaitRelease(act)
}
}
func (syncer *Syncer) DeriveSyncer() *Syncer {
return newSyncer(syncer.ctx, syncer, nil)
}
func (syncer *Syncer) WaitRelease(act SyncerWaitMode) {
switch act {
case SyncerWaitModeAny:
<-syncer.onced
syncer.ctxc()
case SyncerWaitModeCancel:
syncer.ctxc()
case SyncerWaitModeIdle:
}
syncer.wg.Wait()
syncer.fini()
}
func (syncer *Syncer) Async(fSync func(), fBreak func()) {
syncer.increase()
go func() {
syncer.sync(fSync, fBreak)
syncer.decrease()
}()
}
func (syncer *Syncer) Sync(fSync func(), fBreak func()) {
syncer.sync(fSync, fBreak)
syncer.fini()
}
func (syncer *Syncer) sync(fSync func(), fBreak func()) {
done := make(chan bool, 1)
go func() {
fSync()
done <- true
}()
for {
select {
case <-done:
return
case <-syncer.ctx.Done():
fBreak()
<-done
return
}
}
}
func (syncer *Syncer) fini() {
syncer.ctxc()
if syncer.ctxs != nil {
syncer.ctxs()
}
}
func (syncer *Syncer) Ctx() context.Context {
return syncer.ctx
}