面试题答案
一键面试以下是在Go语言中使用context包
实现简单函数超时控制的代码示例:
package main
import (
"context"
"fmt"
"time"
)
func longRunningFunction(ctx context.Context) {
select {
case <-time.After(5 * time.Second):
fmt.Println("Function completed normally")
case <-ctx.Done():
fmt.Println("Function was cancelled due to timeout")
}
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
go longRunningFunction(ctx)
time.Sleep(6 * time.Second)
}
context.WithTimeout
函数的参数及返回值含义
-
参数:
- parent context.Context: 父上下文,通常是
context.Background()
。它是新上下文的祖先,新上下文会继承父上下文的截止时间、取消信号等。 - timeout time.Duration: 表示设置的超时时间。如果在这个时间内没有完成操作,上下文会被取消。
- parent context.Context: 父上下文,通常是
-
返回值:
- ctx context.Context: 新的上下文,它带有超时设置。在超时时间到达后,该上下文会被取消。
- cancel context.CancelFunc: 取消函数。调用这个函数可以手动取消上下文,即使超时时间还未到达。通常在函数结束时(通过
defer
)调用该函数以确保资源被正确清理。