Golang中的上下文-context包的简介及使用
context
包提供了管理并发操作中的取消信号、超时值、键值对等上下文数据的机制。
概述
context
包中的Context
接口提供了以下方法:
Deadline() (deadline time.Time, ok bool)
: 返回上下文被取消的截止日期。Done() <-chan struct{}
: 返回一个channel,当上下文被取消时,该channel会关闭。Err() error
: 返回导致上下文被取消的原因。Value(key interface{}) interface{}
: 返回与上下文关联的键值对。
使用示例
创建带有超时的上下文:
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
// 使用ctx进行操作...
在goroutine中处理超时:
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
go func() {
select {
case <-ctx.Done():
fmt.Println("超时或上下文被取消,退出goroutine。")
return
case <-time.After(20 * time.Second):
fmt.Println("goroutine运行时间超过预定上下文时间。")
}
}()
// 执行其他任务...
在HTTP服务中使用上下文传递请求范围的值:
func MyHandler(w http.ResponseWriter, r *http.Request) {
ctx := context.WithValue(r.Context(), "key", "value")
go HandleRequest(ctx)
}
func HandleRequest(ctx context.Context) {
value := ctx.Value("key")
// 处理value...
}
以上代码展示了如何在Go语言中使用context
包来管理并发操作的上下文,包括创建带有超时和取消功能的上下文、在goroutine中响应上下文的取消信号、在HTTP服务中传递带有键值对的上下文数据。
评论已关闭