Go语言 如果我不取消Context会发生什么?

z4iuyo4d  于 10个月前  发布在  Go
关注(0)|答案(2)|浏览(95)

我有以下代码:

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()放进去会发生什么?go vet警告说
应该调用而不是丢弃context.WithTimeout返回的cancel函数,以避免上下文泄漏
上下文将如何泄露,这将产生什么影响?谢谢

qoefvg9y

qoefvg9y1#

如果取消上下文失败,goroutine that WithCancel or WithTimeout created将无限期地保留在内存中(直到程序关闭),从而导致内存泄漏。如果你经常这样做,你的记忆力会显著膨胀。最佳做法是在调用WithCancel()WithTimeout()后立即使用defer cancel()

lokaqttq

lokaqttq2#

如果使用WithCancelgoroutine 将无限期地保存在内存中。但是,如果您使用WithDeadlineWithTimeout而不调用cancel,则 goroutine 将只保留到计时器到期。
但这仍然不是最佳实践,最好在处理完资源后立即调用cancel

相关问题