如何在 Go 中使用 context.WithTimeout 继承父上下文?
时间:2024-03-20
浏览:368
作者:佚名
在 Go 中,可以通过 `context.WithTimeout` 创建带超时的子上下文。然而,直接重用子上下文会导致父上下文被隐藏,从而导致后续请求出现超时错误。为了解决这个问题,需要使用父上下文来创建新的子上下文,避免覆盖子上下文。
通过 context.withtimeout 重用父上下文并设置新的超时
大家好,我是 go 的新手。我想知道是否可以重用父上下文来创建多个 context.withtimeout()。基本原理是我必须按顺序调用多个网络请求,并且希望使用父级上下文同时为每个请求设置超时。
基本原理
当父上下文被取消时,所有发出的请求也将被取消。
问题
在下面的代码中,它显示了一个示例,其中 longprocess 是网络请求。但是,在 context 超出 截止时间的情况下进行第二次 longprocess 调用之前,上下文已关闭。
文档 withdeadline 指出 当截止日期到期、调用返回的取消函数时或当父上下文的 done 通道关闭时(以先发生者为准),返回的上下文的 done 通道将关闭。
那么如果是这种情况,有没有办法可以重置 withtimeout 的计时器?或者我是否必须为每个请求创建一个新的上下文 context.background() ?这意味着父上下文将不会被传递。 :(
// LongProcess refers to a long network request
func LongProcess(ctx context.Context, duration time.Duration, msg string) error {
c1 := make(chan string, 1)
go func() {
// Simulate processing
time.Sleep(duration)
c1 <- msg
}()
select {
case m := <-c1:
fmt.Println(m)
return nil
case <-ctx.Done():
return ctx.Err()
}
}
func main() {
ctx := context.Background()
t := 2 * time.Second
ctx, cancel := context.WithTimeout(ctx, t)
defer cancel()
// Simulate a 2 second process time
err := LongProcess(ctx, 2*time.Second, "first process")
fmt.Println(err)
// Reusing the context.
s, cancel := context.WithTimeout(ctx, t)
defer cancel()
// Simulate a 1 second process time
err = LongProcess(s, 1*time.Second, "second process")
fmt.Println(err) // context deadline exceeded
}解决方案
看起来第一次调用 context.withtimeout 会隐藏父上下文 ctx。稍后的进程重新使用这个已经取消的上下文,因此出现错误。您必须重新使用父级。这是更新的示例:
func main() {
// Avoid to shadow child contexts
parent := context.Background()
t := 2 * time.Second
// Use the parent context.
ctx1, cancel := context.WithTimeout(parent, t)
defer cancel()
err := LongProcess(ctx1, 2*time.Second, "first process")
fmt.Println(err)
// Use the parent context not the canceled one.
ctx2, cancel := context.WithTimeout(parent, t)
defer cancel()
err = LongProcess(ctx2, 1*time.Second, "second process")
fmt.Println(err)
}以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。
本文内容来源于互联网,如有侵权请联系删除。
近期热门
站内热门
最新文章
热门专题
