go runtime_error ai_generated true

致命错误:所有goroutine都在休眠 - 死锁!(无缓冲通道)

fatal error: all goroutines are asleep - deadlock! (unbuffered channel)

ID: go/unbuffered-channel-blocking

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

版本兼容性

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

根因分析

无缓冲通道要求发送方和接收方同时就绪。如果只有一方就绪,就会无限期阻塞。

English

An unbuffered channel requires both sender and receiver to be ready simultaneously. If only one side is ready, it blocks indefinitely.

generic

解决方案

  1. 90% 成功率 Ensure both sender and receiver are started before the blocking operation
    ch := make(chan int)
    
    go func() {
        val := <-ch
        fmt.Println(val)
    }()
    
    ch <- 42 // now this won't block because receiver is ready
  2. 80% 成功率 Use a buffered channel with a reasonable capacity
    ch := make(chan int, 10) // buffer size 10

无效尝试

常见但无效的做法:

  1. Making the channel buffered with a small size 50% 失败

    A small buffer may not be sufficient; if the buffer fills up, the same deadlock can occur.

  2. Using time.Sleep to give the other side time to prepare 75% 失败

    Sleeping is non-deterministic and doesn't guarantee both sides are ready; it may still deadlock.