Sobes.tech
Junior — Middle

How to implement safe goroutine termination when the expected result is not received, using switch-case construct?

sobes.tech AI

Answer from AI

To safely terminate a goroutine while waiting for a result, you can use a select statement 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("Result received:", result)
    case <-time.After(5 * time.Second):
        fmt.Println("Timeout waiting for result, terminating goroutine")
        return
    case <-done:
        fmt.Println("Received termination signal")
        return
    }
}

Here, the goroutine waits for data from someChannel. If data does not arrive within 5 seconds, a timeout occurs, and the goroutine terminates. You can also send a signal through the done channel for forced termination.

This approach helps avoid goroutine hangs and allows safe control over its termination.

How to implement safe goroutine termination when the… - sobes.tech