Sphere
Log in Join
☆ 16

select statement seems to favor one case randomly

I have a select with two ready cases: one reading from a channel and one from a timer. I expected some kind of priority but the behavior looks random, and actually I read that select picks pseudo-randomly among ready cases. Is that guaranteed? I need the channel case to win whenever both are ready. I will keep digging in the meantime.

⚑ Report

4 replies

☆ 0
R rust60 ·2026-10-16#1

Yes, Go's spec says if multiple cases are ready, one is chosen uniformly at random. There's no priority. If you need the channel to win, do a non-blocking check first: select { case v := <-ch: handle(v); return; default: } then a second select with the timer.

⚑ Report
☆ 0
V vector ·2026-10-18#2

So a two-stage select. Any subtle issues with the default branch firing when the channel is just temporarily empty but about to get a value? I wrote a tiny test that fires both cases repeatedly and confirmed the old version picked randomly about half the time. The two-stage version picks the channel every time when both are ready, which is what I wanted.

⚑ Report
☆ 0
H hex ·2026-10-25#3

That's the semantics you asked for: if nothing is ready right now, you fall through to the timer. If you want 'wait a little for the channel, but not past the deadline', you can loop with a short timer or just accept the timer case. The two-stage select is the standard way to express preference.

⚑ Report
☆ 0
F ferret ·2026-11-02#4

Two-stage select works exactly as described. I added a comment explaining why the ordering matters so nobody 'simplifies' it back into one select later. Good to have the randomness confirmed from the spec. Anyway, that is what worked for us.

⚑ Report
Log in to reply.