-
Notifications
You must be signed in to change notification settings - Fork 0
/
context.go
105 lines (87 loc) · 1.84 KB
/
context.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
package cancelContext
import (
"context"
"sync/atomic"
"time"
)
type (
// 用event模拟的Context,实验性质,请勿使用
// Context struct {
// exitEvent *Event
// }
// 封装标准库context.WithCancel
CancelCtx struct {
context.Context
cancelFunc context.CancelFunc
isDone int32
}
)
var (
ContextDoneError = context.Canceled
)
// closedChan is a reusable closed channel.
var closedChan = make(chan struct{})
func init() {
close(closedChan)
}
// func NewContext() Context {
// return Context{
// exitEvent: NewEvent(),
// }
// }
// func (c Context) Deadline() (time.Time, bool) {
// return time.Time{}, false
// }
// func (c Context) Done() <-chan struct{} {
// return c.exitEvent.Done()
// }
// func (c Context) Err() error {
// if c.exitEvent.IsSet() {
// return ContextDoneError
// } else {
// return nil
// }
// }
// func (c Context) Value(key interface{}) interface{} {
// return nil
// }
// func (c Context) Close() {
// c.exitEvent.Set()
// }
func (me *CancelCtx) Cancel() bool {
if atomic.CompareAndSwapInt32(&me.isDone, 0, 1) {
me.cancelFunc()
return true
}
return false
}
func (me *CancelCtx) Err() error {
if me.isDone != 0 {
return ContextDoneError
} else {
return me.Context.Err()
}
}
func (me *CancelCtx) Done() <-chan struct{} {
if me.isDone != 0 {
return closedChan
}
return me.Context.Done()
}
func ClosedChan() chan struct{} {
return closedChan
}
func NewCancelCtx(parent context.Context) *CancelCtx {
c, f := context.WithCancel(parent)
return &CancelCtx{
Context: c,
cancelFunc: f,
}
}
func NewTimeoutCtx(parent context.Context, timeout time.Duration) *CancelCtx {
c, f := context.WithTimeout(parent, timeout)
return &CancelCtx{
Context: c,
cancelFunc: f,
}
}