-
Notifications
You must be signed in to change notification settings - Fork 0
/
cancel.go
51 lines (42 loc) · 1007 Bytes
/
cancel.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
package signal
import (
"sync"
)
// CancelSignal is a signal passed to goroutine, in order to cancel the goroutine on demand.
type CancelSignal struct {
cancel chan struct{}
done sync.WaitGroup
}
// NewCloseSignal creates a new CancelSignal.
func NewCloseSignal() *CancelSignal {
return &CancelSignal{
cancel: make(chan struct{}),
}
}
func (v *CancelSignal) WaitThread() {
v.done.Add(1)
}
// Cancel signals the goroutine to stop.
func (v *CancelSignal) Cancel() {
close(v.cancel)
}
func (v *CancelSignal) Cancelled() bool {
select {
case <-v.cancel:
return true
default:
return false
}
}
// WaitForCancel should be monitored by the goroutine for when to stop.
func (v *CancelSignal) WaitForCancel() <-chan struct{} {
return v.cancel
}
// FinishThread signals that current goroutine has finished.
func (v *CancelSignal) FinishThread() {
v.done.Done()
}
// WaitForDone is used by caller to wait for the goroutine finishes.
func (v *CancelSignal) WaitForDone() {
v.done.Wait()
}