面试题答案
一键面试基本步骤
- 创建一个带有超时的
context.Context
。通常使用context.WithTimeout
函数,它接受一个父context
(通常是context.Background()
)和一个超时时间。 - 将创建的
context
传递给需要设置超时的函数。 - 在被调用的函数内部,定期检查
context
的Done
通道,以判断是否超时。如果Done
通道接收到值,说明已经超时,函数应停止当前操作并返回。
代码示例
package main
import (
"context"
"fmt"
"time"
)
func longRunningFunction(ctx context.Context) error {
select {
case <-time.After(2 * time.Second): // 模拟一个长时间运行的任务
return nil
case <-ctx.Done():
return ctx.Err()
}
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
err := longRunningFunction(ctx)
if err != nil {
fmt.Println("Function timed out:", err)
} else {
fmt.Println("Function completed successfully")
}
}
在上述代码中:
context.WithTimeout(context.Background(), 1*time.Second)
创建了一个带有1秒超时的context
,并返回ctx
和cancel
函数,cancel
函数用于手动取消context
(这里使用defer
确保函数结束时无论是否超时都会取消context
)。longRunningFunction
函数内部使用select
语句监听time.After(2 * time.Second)
和ctx.Done()
。如果ctx.Done()
先接收到值,说明超时,函数返回ctx.Err()
。- 在
main
函数中调用longRunningFunction
,并根据返回的错误判断函数是否超时。