Junior — Middle
How can you stop a goroutine after a specified time if the result has not been received?
sobes.tech AI
Answer from AI
In Go, to stop a goroutine after a specified timeout, you typically use select with a timer or a context with timeout.
Example with time.After:
select {
case result := <-ch:
// handle result
case <-time.After(2 * time.Second):
// timeout - no result received within 2 seconds
}
Example with context:
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
select {
case result := <-ch:
// handle result
case <-ctx.Done():
// timeout or cancellation
}
Thus, if the result does not arrive in time, execution can be canceled and timeout handled.