go runtime_error ai_generated true

bug: select picks random case, message reordering observed

ID: go/select-random-case-when-multiple-ready

Also available as: JSON · Markdown · 中文
80%Fix Rate
85%Confidence
0Evidence
2024-08-14First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.x active — — —

Root Cause

When multiple select cases are ready, Go picks one pseudo-randomly. Code assuming deterministic ordering or priority breaks.

generic

中文

当多个 select case 同时就绪时,Go 伪随机选择一个。假设确定性顺序或优先级的代码会出错。

Workarounds

  1. 90% success
    select {
    case v := <-highPriority:
        handle(v)
    default:
        select {
        case v := <-highPriority:
            handle(v)
        case v := <-lowPriority:
            handle(v)
        }
    }
  2. 85% success
    type msg struct { prio int; body any }
    // single channel; consumer sorts or dispatches by prio

Dead Ends

Common approaches that don't work:

  1. 95% fail

    Go does not honor case order for priority; selection is random.

  2. 90% fail

    Doesn't affect select semantics and adds latency.