go resource_error ai_generated true

警告:goroutine 在循环中休眠(goroutine 9)

warning: goroutine sleeping in loop (goroutine 9)

ID: go/goroutine-sleep-in-loop

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

版本兼容性

版本状态引入弃用备注
1.20 active

根因分析

goroutine 在紧密循环中调用 time.Sleep,消耗资源并可能阻塞。

English

A goroutine calls time.Sleep in a tight loop, consuming resources and potentially blocking.

generic

解决方案

  1. 90% 成功率
    ticker := time.NewTicker(time.Second)
    defer ticker.Stop()
    for range ticker.C {
        // do work
    }
  2. 85% 成功率
    select {
    case <-time.After(time.Second):
        // do work
    case <-ctx.Done():
        return
    }

无效尝试

常见但无效的做法:

  1. 80% 失败

    Still busy-waits; doesn't solve the underlying issue.

  2. 70% 失败

    Gosched doesn't block; it just yields, but loop continues.

  3. 90% 失败

    Wastes CPU and may cause performance issues.