@@ -13,14 +13,10 @@ import (
1313// # REFERENCES
1414// - https://pkg.go.dev/context@go1.20.1#WithCancelCause
1515func WithContextCancelCause () error {
16- var (
17- rootCtx = context .Background ()
18- mainCtx , mainCxl = context .WithTimeout (rootCtx , 2 * time .Second )
19- procCtx context.Context
20- )
16+ mainCtx , mainCxl := context .WithTimeout (context .Background (), 1 * time .Second )
2117 defer mainCxl ()
2218
23- procCtx = func (ctx context.Context ) context.Context {
19+ withCancelCauseCtx : = func (ctx context.Context ) context.Context {
2420 //
2521 // Go 1.20 から WithCancelCause() が追加された
2622 // これにより、cancel 関数に対して任意のエラーを指定出来るようになっている
@@ -31,26 +27,47 @@ func WithContextCancelCause() error {
3127 ctx , cxl := context .WithCancelCause (ctx )
3228
3329 go func () {
34- <- time .After (1 * time .Second )
35- cxl (fmt .Errorf ("my error" ))
30+ select {
31+ case <- time .After (500 * time .Millisecond ):
32+ cxl (fmt .Errorf ("my error" ))
33+ case <- ctx .Done ():
34+ }
3635 }()
3736
3837 return ctx
3938 }(mainCtx )
4039
40+ withCancelCtx := func (ctx context.Context ) context.Context {
41+ ctx , cxl := context .WithCancel (ctx )
42+
43+ go func () {
44+ select {
45+ case <- time .After (2 * time .Second ):
46+ cxl ()
47+ case <- ctx .Done ():
48+ }
49+ }()
50+
51+ return ctx
52+ }(withCancelCauseCtx )
53+
4154 select {
42- case <- procCtx .Done ():
55+ case <- withCancelCtx .Done ():
56+ case <- withCancelCauseCtx .Done ():
4357 case <- mainCtx .Done ():
4458 }
4559
46- output .Stdoutl ("[procctx.Err]" , procCtx .Err ())
47- output .Stdoutl ("[mainctx.Err]" , mainCtx .Err ())
60+ output .Stdoutl ("[withCancelCtx.Err ]" , withCancelCtx .Err ())
61+ output .Stdoutl ("[withCancelCauseCtx.Err ]" , withCancelCauseCtx .Err ())
62+ output .Stdoutl ("[mainCtx.Err ]" , mainCtx .Err ())
4863
4964 // 当然であるが、下位のコンテキストで設定した任意のエラーは
5065 // 上位のコンテキストを指定しても取得できない。
51- output .Stdoutl ("[procctx.Cause]" , context .Cause (procCtx ))
52- output .Stdoutl ("[mainctx.Cause]" , context .Cause (mainCtx ))
53- output .Stdoutl ("[rootctx.Cause]" , context .Cause (rootCtx ))
66+ // 下位のコンテキストには伝播する。
67+ output .StdoutHr ()
68+ output .Stdoutl ("[withCancelCtx.Cause ]" , context .Cause (withCancelCtx ))
69+ output .Stdoutl ("[withCancelCauseCtx.Cause]" , context .Cause (withCancelCauseCtx ))
70+ output .Stdoutl ("[mainCtx.Cause ]" , context .Cause (mainCtx ))
5471
5572 return nil
5673}
0 commit comments