Sobes.tech
Junior — Middle

Kuidas õigesti peatada jooksvat goroutine, kui on vaja, et see lõpeb välise signaali või tingimuse põhjal, isegi kui tulemust veel ei ole saadud?

sobes.tech AI

Vastus AI-lt

Correctly stopping a running goroutine based on an external signal or condition in Go typically involves using a context (context.Context) or channels to transmit the cancellation signal.

Example using context:

func worker(ctx context.Context) {
    for {
        select {
        case <-ctx.Done():
            // Cancellation signal received, ending goroutine
            return
        default:
            // Perform work
        }
    }
}

func main() {
    ctx, cancel := context.WithCancel(context.Background())
    go worker(ctx)

    // At some point, call cancel() to stop the goroutine
    cancel()
}

This approach allows the goroutine to regularly check if a stop signal has been sent and to terminate properly, even if the result has not yet been received. Similarly, a channel can be used to transmit the stop signal, but context is a more idiomatic and convenient way in Go.