Junior — Middle
How does a goroutine recognize that its execution has been canceled via context?
sobes.tech AI
Answer from AI
Goroutines in Go recognize cancellation through the context.Context using the Done() channel, which is closed upon cancellation.
When a cancellable context is created (for example, via context.WithCancel or context.WithTimeout), the goroutine can listen to the ctx.Done() channel:
ctx, cancel := context.WithCancel(context.Background())
// Launch goroutine
go func() {
select {
case <-ctx.Done():
// Context is canceled, need to terminate
fmt.Println("Goroutine canceled")
return
default:
// Perform main work
}
}()
// Cancel the context
cancel()
Thus, the goroutine detects cancellation by checking the Done() channel and can terminate properly.