Junior — Middle
How can you stop a goroutine if the expected value has not been reached yet?
sobes.tech AI
Answer from AI
In Go, to stop a goroutine that is waiting for a value but that value may not arrive, channels with timeout or a cancellable context are usually used.
Example with timeout using select and time.After:
select {
case val := <-ch:
// received value, continue work
case <-time.After(time.Second * 5):
// timeout, stop the goroutine
}
Another way is to use a context (context.Context), which can be canceled from outside:
ctx, cancel := context.WithCancel(context.Background())
go func() {
select {
case val := <-ch:
// process val
case <-ctx.Done():
// stop the goroutine
}
}()
// somewhere in the code, call cancel() to stop the goroutine
Thus, the goroutine will not wait indefinitely and can terminate correctly.