-
Notifications
You must be signed in to change notification settings - Fork 0
/
exited_notifier.go
59 lines (51 loc) · 1.17 KB
/
exited_notifier.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
package chanUtils
import (
"context"
"sync/atomic"
)
// ExitedNotifier When you call Finish(), all waiting goroutines will be resumed.
type ExitedNotifier struct {
Channel chan bool
exited int32
}
// Finish resumes all waiting goroutines
func (en *ExitedNotifier) Finish() {
if atomic.AddInt32(&en.exited, 1) == 1 {
close(en.Channel)
}
}
// Wait waits Finish() is called.
func (en *ExitedNotifier) Wait() {
<-en.Channel
}
// WaitWithContext waits until Finish() is called or ctx is triggered.
func (en *ExitedNotifier) WaitWithContext(ctx context.Context) {
select {
case <-ctx.Done():
case <-en.Channel:
}
}
// TriggerOrCancel sets f() to be called when Finish() is called.
// The returned function is a canceller.
// Note that you must call this when you no longer need f() to be called.
func (en *ExitedNotifier) TriggerOrCancel(f func()) func() {
canceler := make(chan bool)
go func() {
select {
case <-en.Channel:
f()
case <-canceler:
return
}
}()
return func() {
close(canceler)
}
}
// NewExitedNotifier creates a new ExitedNotifier
func NewExitedNotifier() *ExitedNotifier {
return &ExitedNotifier{
Channel: make(chan bool),
exited: 0,
}
}