Sobes.tech
Senior

How does context.WithCancel work with cancellation?

sobes.tech AI

Answer from AI

context.WithCancel in Go creates a new context that can be manually canceled. It returns two values: the new context and a cancel function cancel(). When cancel() is called, all operations listening to this context (for example, through <-ctx.Done()) receive a cancellation signal and can terminate properly.

Example usage:

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

// Launch a goroutine that listens for cancellation
go func() {
    <-ctx.Done() // wait for cancellation signal
    fmt.Println("Cancellation received, terminating")
}()

// Cancel the context after some time
cancel()

Thus, WithCancel allows coordinating operation cancellations and resource cleanup, which is especially useful for managing the lifecycle of goroutines.

How does context.WithCancel work with cancellation… - sobes.tech