go resource_error ai_generated true

错误:CPU 占用 100%:带 default 的 select 在紧密循环中空转

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

ID: go/select-default-busy-loop

其他格式: JSON · Markdown 中文 · English
80%修复率
87%置信度
0证据数
2024-08-15首次发现

版本兼容性

版本状态引入弃用备注
1.18 active — — —
1.22 active — — —

根因分析

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

English

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

解决方案

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

无效尝试

常见但无效的做法:

  1. 80% 失败

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

  2. 85% 失败

    Starves other goroutines and hides rather than fixes the spin