Junior — Middle
Kuidas turvaliselt lõpetada goroutine, kui oodatud tulemust ei saadud, kasutades switch-case struktuuri?
sobes.tech AI
Vastus AI-lt
To safely terminate a goroutine while waiting for a result, you can use the select construct with multiple cases, including a timeout or a cancellation signal. In Go, there is no direct switch-case for channels, but select performs a similar function.
Example with a timeout:
func worker(done chan struct{}) {
select {
case result := <-someChannel:
fmt.Println("Received result:", result)
case <-time.After(5 * time.Second):
fmt.Println("Timeout reached, ending goroutine")
return
case <-done:
fmt.Println("Received termination signal")
return
}
}
Here, the goroutine waits for data from someChannel. If the data does not arrive within 5 seconds, the timeout triggers and the goroutine ends. You can also send a signal via the done channel to forcibly terminate it.
This approach prevents the goroutine from hanging and allows you to control it safely.