go resource_error ai_generated true

error: CPU at 100%: select with default spins in tight loop

ID: go/select-default-busy-loop

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.18 active — — —
1.22 active — — —

Root Cause

A 'for { select { case ...: default: } }' loop with a default branch never blocks, so it consumes a full CPU core spinning when no case is ready.

generic

中文

带有 default 分支的 'for { select { case ...: default: } }' 循环永不阻塞,当没有 case 就绪时它会占满一个 CPU 核心空转。

Workarounds

  1. 95% success
    Remove the default branch so select blocks until a case is ready
  2. 85% success
    If polling is required, add a time.After backoff: 'case <-time.After(100*time.Millisecond):'

Dead Ends

Common approaches that don't work:

  1. 80% fail

    Yields but still spins at high CPU; just slightly less hot

  2. 85% fail

    Starves other goroutines and hides rather than fixes the spin