File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -49,7 +49,11 @@ type hchan struct {
4949
5050#### 通道死锁
5151
52- - 当无缓存通道,不具备同时写入和读取就绪的情况下,写入数据或者读取数据
53- - 全部取出的管道,再取会出现死锁
54- - 已经塞满的管道,在塞也会死锁
55- - 重复关闭
52+ | ** 死锁场景** | ** 关键原因** | ** 解决方案** |
53+ | --------------------------| --------------------------------------------| ----------------------------------------------------------------------------|
54+ | ** 同步操作顺序错误** | 无缓冲通道的发送/接收未配对或未异步执行 | 使用缓冲通道,或确保发送/接收操作异步执行(用 ` go ` 启动协程) |
55+ | ** 未关闭通道导致循环阻塞** | 接收方在 ` for range ` 中等待未关闭的通道 | 发送完成后显式关闭通道(` close(ch) ` ),或通过其他逻辑退出循环 |
56+ | ** 缓冲通道已满** | 发送数据超过缓冲区且无接收方消费 | 增大缓冲区,或启动接收协程及时消费数据 |
57+ | ** ` select ` 永久阻塞** | 所有 ` case ` 分支阻塞且无 ` default ` 分支 | 添加 ` default ` 分支(非阻塞模式)或设置超时(` time.After ` ) |
58+ | ** 协程间循环等待** | 多个协程互相等待对方发送数据 | 重构逻辑避免循环依赖,或引入超时机制(` context ` /` time.After ` )强制退出 |
59+ | ** 未处理通道关闭** | 接收方未检测通道关闭,导致死循环 | 使用 ` val, ok := <-ch ` 检测通道状态,或通过 ` for range ` 自动退出(需发送方关闭通道) |
You can’t perform that action at this time.
0 commit comments