go resource_error ai_generated true

warning: goroutine sleeping in loop (goroutine 9)

ID: go/goroutine-sleep-in-loop

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.20 active

Root Cause

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

generic

中文

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

Workarounds

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

Dead Ends

Common approaches that don't work:

  1. 80% fail

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

  2. 70% fail

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

  3. 90% fail

    Wastes CPU and may cause performance issues.