Junior — Middle
How can you forcibly terminate all running goroutines in a program?
sobes.tech AI
Answer from AI
Go does not have a built-in way to forcibly terminate all goroutines, as they lack an external force stop mechanism. To manage the lifecycle of goroutines, contexts (context.Context) or channels are typically used for signaling completion.
General approach:
- Create a
context.WithCancelor a channel. - Pass it to goroutines.
- When needed, call
cancel()or close the channel to signal goroutines to finish.
Example:
ctx, cancel := context.WithCancel(context.Background())
go func(ctx context.Context) {
for {
select {
case <-ctx.Done():
return // End the goroutine
default:
// Goroutine work
}
}
}(ctx)
// When you need to stop all goroutines
cancel()
Thus, the termination of goroutines is controlled by the goroutine code itself, not externally.