Go语言并发与Web服务开发
1. Go语言并发编程
Go语言的并发编程是其强大特性之一,下面将介绍几个重要的并发概念和相关代码示例。
1.1 上下文取消与超时处理
在Go 1.21中引入了 context.WithCancelCause() 方法,它能让我们自定义取消原因,以下是示例代码:
package main
import (
"context"
"errors"
"fmt"
"time"
)
func main() {
ctx := context.Background()
ctx, cancel := context.WithCancelCause(ctx)
cancel(errors.New("Canceled by timeout"))
err := takingTooLong(ctx)
if err != nil {
fmt.Println(err)
return
}
}
func takingTooLong(ctx context.Context) error {
select {
case <-time.After(3 * time.Second):
fmt.Println("Done!")
return nil
case <-ctx.Done():
fmt.Println("Canceled!")
return context.Caus
超级会员免费看
订阅专栏 解锁全文

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



