-
Notifications
You must be signed in to change notification settings - Fork 0
/
impl_1.18.go
58 lines (47 loc) · 1.28 KB
/
impl_1.18.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
//go:build go1.18 && !go1.21
// +build go1.18,!go1.21
package cancelContext
import (
"context"
"runtime"
"sync/atomic"
"github.com/szmcdull/go-forceexport"
)
type (
canceler interface {
cancel(removeFromParent bool, err error)
Done() <-chan struct{}
}
)
var (
//newCancelCtx func(parent context.Context) cancelCtx
propagateCancel func(parent context.Context, child canceler)
)
func init() {
// context.WithCancel(context.Background())
// if err := forceexport.GetFunc(&newCancelCtx, `context.newCancelCtx`); err != nil {
// panic(err)
// }
f := runtime.Func{}
_ = &f
if err := forceexport.GetFunc(&propagateCancel, `context.propagateCancel`); err != nil {
panic(err)
}
}
func (me *CancelCtx) cancel(removeFromParent bool, err error) {
if atomic.CompareAndSwapInt32(&me.isDone, 0, 1) {
me.cancelFunc()
}
}
// 将多个Context聚合在一起,任意一个parent Done,聚合Context都会Done
func (parent *CancelCtx) NewLinkedCancelCtx(otherParents ...context.Context) *CancelCtx {
count := len(otherParents)
// if count == 0 {
// panic(`at least 1 ctx expected`)
// }
withCancel := NewCancelCtx(parent)
for i := 0; i < count; i++ {
propagateCancel(otherParents[i], withCancel)
}
return withCancel
}