实现说明
完整样例的代码结构以函数为核心展开 CloseWithReason、runTask、main组织。
工作交给 goroutine 执行,结果通过 channel 传回,两个执行上下文之间的交接是安全的。清理逻辑用 defer 挂载,函数的任何退出路径都会执行。
使用要点
- 无任何外部软件依赖——所用的每一处 API 都由运行时提供。
- 跑完文件,输出里会留下标记——
early path err:、canceled path err:。 main按顺序串起runTask;运行文件就会把这个流程跑一遍。
常见问题
运行「用 context.AfterFunc 的 stop 取消清理回调」会打印什么?
不用做任何设置,直接把文件跑完——输出里的 early path err:、canceled path err: 标签标明各步骤。
主签名形如 func (r *Resource) CloseWithReason(reason string) bool
核心语句
go func() { cancel2(errors.New("deadline-hit")) }()
return context.Cause(ctx)
func (r *Resource) CloseWithReason(reason string) bool {
r.mu.Lock()
defer r.mu.Unlock()
if r.closed {
return false
}
r.closed = true
fmt.Printf("[%s] closed by %s\n", r.name, reason)
return true
}
代码示例
package main
import (
"context"
"errors"
"fmt"
"sync"
)
type Resource struct {
name string
mu sync.Mutex
closed bool
}
func (r *Resource) CloseWithReason(reason string) bool {
r.mu.Lock()
defer r.mu.Unlock()
if r.closed {
return false
}
r.closed = true
fmt.Printf("[%s] closed by %s\n", r.name, reason)
return true
}
func runTask(ctx context.Context, res *Resource, finishEarly bool) error {
stopped := make(chan struct{})
stop := context.AfterFunc(ctx, func() {
defer close(stopped)
res.CloseWithReason("AfterFunc:" + context.Cause(ctx).Error())
})
defer func() {
if !stop() {
<-stopped
}
}()
if finishEarly {
res.CloseWithReason("normal-completion")
return nil
}
<-ctx.Done()
return context.Cause(ctx)
}
func main() {
r1 := &Resource{name: "conn-1"}
ctx1, cancel1 := context.WithCancelCause(context.Background())
fmt.Println("early path err:", runTask(ctx1, r1, true))
cancel1(errors.New("late-cancel"))
r2 := &Resource{name: "conn-2"}
ctx2, cancel2 := context.WithCancelCause(context.Background())
go func() { cancel2(errors.New("deadline-hit")) }()
fmt.Println("canceled path err:", runTask(ctx2, r2, false))
}