forked from ravendb/ravendb-go-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cancellation_token_source.go
61 lines (49 loc) · 1.32 KB
/
cancellation_token_source.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
package ravendb
import (
"sync/atomic"
"time"
)
// TODO: make private if not exposed in public API
// TODO: CancellationToken seems un-necessary
type CancellationTokenSource struct {
cancelled int32
timeDeadlineNanoSec int64
}
func NewCancellationTokenSource() *CancellationTokenSource {
return &CancellationTokenSource{}
}
func (s *CancellationTokenSource) getToken() *CancellationToken {
return &CancellationToken{
token: s,
}
}
func (s *CancellationTokenSource) cancel() {
atomic.StoreInt32(&s.cancelled, 1)
}
func (s *CancellationTokenSource) cancelAfter(timeoutInMilliseconds int) {
dur := time.Millisecond * time.Duration(timeoutInMilliseconds)
t := time.Now().Add(dur)
atomic.StoreInt64(&s.timeDeadlineNanoSec, t.UnixNano())
}
type CancellationToken struct {
token *CancellationTokenSource
}
func (t *CancellationToken) isCancellationRequested() bool {
v := atomic.LoadInt32(&t.token.cancelled)
if v != 0 {
return true
}
timeDeadlineNanoSec := atomic.LoadInt64(&t.token.timeDeadlineNanoSec)
if 0 == timeDeadlineNanoSec {
return false
}
timeDeadline := time.Unix(0, timeDeadlineNanoSec)
isAfter := time.Now().After(timeDeadline)
return isAfter
}
func (t *CancellationToken) throwIfCancellationRequested() error {
if t.isCancellationRequested() {
return NewOperationCancelledException("")
}
return nil
}