when I create a context WithCancel function by golang,why suggest to run the cancelFunc at the end of the function。
I think,assume I use gin framework, After current function run finished,the context of gin will destory。So is it necessary to run the cancelFunc after
define context.WithCancel(ctx) , defer cancelFunc()
func myFunction(ctx *context.Context) error {
cancelCtx, cancelFunc := context2.WithCancel(ctx)
defer cancelFunc()
var (
successTask = int32(0)
failTask = int32(0)
wg = &sync.WaitGroup{}
)
select {
case <-cancelCtx.Done():
break
default:
for i := 0; i < 100; i++{
wg.add(1)
go func(){
defer wg.Done()
err := myLogic()
if err != nil {
atomic.AddInt32(&failTask, 1)
cancelFunc()
return
}
atomic.AddInt32(&successTask, 1)
}
}
}
wg.Wait()
return nil
}
the code defer cancelFunc(),can i remove this line?
Documentation of
context.WithCancel()states you should callcancel(), so you should, end of discussion:The implementation of
context.WithCancel()may allocate resources or launch goroutines to propagate cancellation, so since the implementation is not in your hands, you should callcancel().Even if in the current version (with current implementation) wouldn't make a difference, you have no guarantee that with a future (or older) version it would still work as intended (e.g. not leaking resources) without calling
cancel().