Junior — Middle
Kuidas peatada goroutine'i täitmine määratud aja möödumisel, kui tulemust ei ole saadud?
sobes.tech AI
Vastus AI-lt
In Go, to stop the execution of a goroutine after a specified time, select with a timer or a context with a timeout is usually used.
Example with time.After:
select {
case result := <-ch:
// process result
case <-time.After(2 * time.Second):
// timeout — result not received within 2 seconds
}
Example with context:
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
select {
case result := <-ch:
// process result
case <-ctx.Done():
// timeout or cancellation
}
This way, if the result does not arrive in time, execution can be interrupted and the timeout handled.