gpt4 book ai didi

go - 如果我不取消上下文会发生什么?

转载 作者:IT老高 更新时间:2023-10-28 13:04:09 26 4
gpt4 key购买 nike

我有以下代码:

func Call(ctx context.Context, payload Payload) (Response, error) {
req, err := http.NewRequest(...) // Some code that creates request from payload
ctx, cancel = context.withTimeout(ctx, time.Duration(3) * time.Second)
defer cancel()
return http.DefaultClient.Do(req)
}

如果我不把 defer cancel() 放在那里会怎样? 去检查警告这个

the cancel function returned by context.WithTimeout should be called, not discarded, to avoid a context leak

上下文将如何泄露,这将产生什么影响?谢谢

最佳答案

如果您未能取消上下文,goroutine that WithCancel or WithTimeout created将无限期地保留在内存中(直到程序关闭),导致内存泄漏。如果你经常这样做,你的内存就会显着膨胀。最好在调用 WithCancel()WithTimeout()

后立即使用 defer cancel()

关于go - 如果我不取消上下文会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44393995/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com