面试题答案
一键面试1. WithTimeout函数适用场景
- 控制请求处理时间:在处理HTTP请求时,限制处理该请求的最长时间,防止处理过程中出现无限等待或长时间阻塞,导致服务响应缓慢影响其他请求。
- 限制函数执行时间:对于一些可能长时间运行的函数,如数据库查询、远程调用等,通过设置超时时间,避免函数执行时间过长占用过多资源。
2. 实现设置超时功能原理
WithTimeout
函数创建一个带有超时的 Context
。当超时时间到达,该 Context
会被取消,基于此 Context
创建的所有子 Context
也会被取消,以此通知所有依赖该 Context
的操作停止。
3. 代码示例
package main
import (
"context"
"fmt"
"time"
)
func main() {
// 创建一个带有5秒超时的Context
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel() // 确保在函数结束时取消,释放资源
go func(ctx context.Context) {
select {
case <-time.After(10 * time.Second):
fmt.Println("任务完成(模拟长时间任务)")
case <-ctx.Done():
fmt.Println("任务超时:", ctx.Err())
}
}(ctx)
// 主线程等待一段时间,确保子goroutine有机会执行
time.Sleep(7 * time.Second)
}
在上述代码中,context.WithTimeout
创建了一个带有5秒超时的 Context
。子 goroutine
模拟一个可能长时间运行的任务,通过 select
监听任务完成(time.After
)和 Context
的取消信号(ctx.Done()
)。当超过5秒时,Context
被取消,子 goroutine
收到取消信号并打印超时信息。