推荐答案
// www.javascriptcn.com code example
package main
import (
"context"
"fmt"
"time"
)
func main() {
// 使用 context.WithTimeout 设置超时
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
select {
case <-time.After(3 * time.Second):
fmt.Println("操作完成")
case <-ctx.Done():
fmt.Println("操作超时:", ctx.Err())
}
// 使用 context.WithDeadline 设置截止时间
deadline := time.Now().Add(2 * time.Second)
ctx2, cancel2 := context.WithDeadline(context.Background(), deadline)
defer cancel2()
select {
case <-time.After(3 * time.Second):
fmt.Println("操作完成")
case <-ctx2.Done():
fmt.Println("操作超时:", ctx2.Err())
}
}本题详细解读
context.WithTimeout
context.WithTimeout 用于创建一个带有超时时间的上下文。它接受两个参数:父上下文和超时时间。当指定的时间过去后,上下文会自动取消,并返回一个 context.CancelFunc 函数,用于手动取消上下文。
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel()
在上面的代码中,ctx 是一个带有 2 秒超时的上下文。如果在 2 秒内没有完成操作,ctx.Done() 会返回一个通道,表示上下文已取消。
context.WithDeadline
context.WithDeadline 用于创建一个带有截止时间的上下文。它接受两个参数:父上下文和截止时间。当达到指定的截止时间时,上下文会自动取消,并返回一个 context.CancelFunc 函数,用于手动取消上下文。
deadline := time.Now().Add(2 * time.Second) ctx2, cancel2 := context.WithDeadline(context.Background(), deadline) defer cancel2()
在上面的代码中,ctx2 是一个带有 2 秒后截止时间的上下文。如果在截止时间之前没有完成操作,ctx2.Done() 会返回一个通道,表示上下文已取消。
区别
context.WithTimeout是基于当前时间加上指定的超时时间来设置截止时间。context.WithDeadline是直接指定一个具体的截止时间。
两者都可以用于控制操作的超时或截止时间,选择使用哪一个取决于具体的需求。