Go语言并发与Web服务开发
1. Go语言并发编程
在Go语言的并发编程中, time.After() 函数的输出长行代表其返回值,显示了 After() 函数在返回的通道上发送当前时间的时刻,这些都表明程序运行正常。若定义较大的延迟,程序输出示例如下:
$ go run useContext.go 13
Delay: 13
f1() Done: context canceled
f2() Done: context canceled
f3() Done: context canceled
这表明程序执行出现延迟时会被取消操作。
1.1 context.WithCancelCause方法
Go 1.21 引入了 context.WithCancelCause() 方法,其主要优势在于提供了定制化功能,这是 context 包中其他方法所不具备的,除此之外,它的行为与 WithCancel() 类似。以下是使用示例:
func main() {
ctx := context.Background()
ctx, cancel := context.WithCancelCause(ctx)
cancel(errors.New("Canceled by timeout"))
err := takingToo
超级会员免费看
订阅专栏 解锁全文

被折叠的 条评论
为什么被折叠?



