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?