I know that if there are more than one "communications" that can proceed in a select statement that one is chosen randomly. I am trying to find an alternative approach that can prefer one "communication" over another.
The background is that I am sending values in a go-routine on a channel which is killed using a context. When I kill it I want the channel to be immediately closed but currently the code will sometimes send a final value on the chan before closing it.
Here is a simplified version of the code:
ctx, cancel := context.WithCancel(context.Background())
ch := make(chan int)
go func() {
defer close(ch)
for i := 1; ; i++ {
select {
case <-ctx.Done():
return
case ch <- i:
}
}
}()
print(<-ch)
print(<-ch)
cancel()
print(<-ch)
print(<-ch)
This sometimes prints 1200 but usually 1230. Try it on the playground
Are there any ideas on how to reorganise the code to favour the first case? (Ie have it always print 1200.)