-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcancelable.go
51 lines (41 loc) · 882 Bytes
/
cancelable.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 multilimiter
import (
"sync"
"sync/atomic"
)
//TODO: This interface may just be a waste, it's not being used right now
type Cancelable interface {
Cancel() bool
IsCanceled() bool
Done() <-chan struct{}
}
var _ Cancelable = (*Canceler)(nil)
func NewCanceler() *Canceler {
return &Canceler{
done: make(chan struct{}),
}
}
type Canceler struct {
isCanceled int32
mu sync.Mutex
done chan struct{}
}
// Cancels
// returns true if we were already canceled; otherwise false
func (me *Canceler) Cancel() bool {
me.mu.Lock()
defer me.mu.Unlock()
alreadyCanceled := me.isCanceled
atomic.StoreInt32(&me.isCanceled, 1)
if alreadyCanceled == 1 {
return true
}
close(me.done)
return false
}
func (me *Canceler) IsCanceled() bool {
return atomic.LoadInt32(&me.isCanceled) == 1
}
func (me *Canceler) Done() <-chan struct{} {
return me.done
}