Sobes.tech
Senior

How to correctly cancel a context in a goroutine?

sobes.tech AI

Answer from AI

In Go, to cancel a context in a goroutine, a cancelable context created with context.WithCancel or context.WithTimeout is usually used. To properly cancel the context, you need to call the cancel function (cancel()) from the goroutine that controls the lifecycle of the operation.

Example:

ctx, cancel := context.WithCancel(context.Background())

go func() {
    defer cancel() // cancel the context when the goroutine finishes
    // work with ctx
    select {
    case <-ctx.Done():
        // handle cancellation
        return
    }
}()

// somewhere else, you can call cancel() to cancel the context
// cancel()

Important:

  • Call cancel() to avoid resource leaks.
  • The goroutine should listen to ctx.Done() to respond correctly to cancellation.
  • If the context is passed to a function that starts a goroutine, usually the cancel function is called from outside, and the goroutine reacts to ctx.Done().
How to correctly cancel a context in a goroutine… - sobes.tech