4 ms·
The best there is with the context package is to make sure to call the cancel function given to you by contexts that have cancelation. Usually you do this via d
by thwarted 7y ago
The best there is with the context package is to make sure to call the cancel function given to you by contexts that have cancelation. Usually you do this via defer. The cancel function is a no-op if the context is finished otherwise. All this ends up doing though is making sure that things that clean themselves up know to clean themselves up eventually.
- morelisp 7y ago> Usually you do this via defer. I agree this is usually done by defer, but you probably should not do it that way unless your code is very simple. Consider a function body which I've seen variants of many times: ctx, cancel = context.WithTimeout(pctx, timeout) defer cancel() if resp, err := do(ctx, req); err == nil { process(resp) } return err Safe yes, but optimal? process doesn't use the context, and may take longer than the timeout. The context will continue running, with some associated resource cost (at the very least, the context's goroutine and timer). A minimal change is: ctx, cancel = context.WithTimeout(pctx, timeout) resp, err := do(ctx, req) cancel() if err == nil { process(resp) } return err Which disposes of those resources much earlier. (Depending on your Go compiler version there is also a potential cost associated simply with using defer; this is independent of that.)