面试题答案
一键面试在Go语言中,context
通过以下方式帮助进行资源管理:
- 取消信号传递:
context
可以在父context
取消时,自动向子context
传递取消信号,使得相关的资源(如goroutine、数据库连接等)能够及时释放。 - 超时控制:可以设置
context
的超时时间,当超时发生时,所有依赖该context
的操作都应该停止并释放资源。
以下是结合HTTP服务器处理请求场景的示例:
package main
import (
"context"
"fmt"
"net/http"
"time"
)
func handler(w http.ResponseWriter, r *http.Request) {
// 创建带有5秒超时的context
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
defer cancel() // 确保函数结束时取消context,释放资源
// 模拟一个可能长时间运行的任务
select {
case <-time.After(10 * time.Second):
fmt.Fprintf(w, "任务完成")
case <-ctx.Done():
fmt.Fprintf(w, "任务超时")
}
}
func main() {
http.HandleFunc("/", handler)
fmt.Println("Server listening on :8080")
http.ListenAndServe(":8080", nil)
}
在上述代码中:
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
创建了一个带有5秒超时的context
,并生成了取消函数cancel
。defer cancel()
确保在函数结束时调用cancel
,无论任务是否超时,都能及时清理资源。- 使用
select
语句监听任务完成信号time.After(10 * time.Second)
和ctx.Done()
。如果任务在5秒内未完成,ctx.Done()
通道会收到信号,表明超时,从而及时终止任务并释放相关资源。