gogo-contextgo-gin

Why run cancelFunc() at the end of the function


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?


Solution

  • Documentation of context.WithCancel() states you should call cancel(), so you should, end of discussion:

    Canceling this context releases resources associated with it, so code should call cancel as soon as the operations running in this Context complete.

    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 call cancel().

    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().