说明无缓冲 channel 的同步语义、所有 goroutine 阻塞时的 deadlock 报错,以及 select + default/超时 的用法。
fatal error: all goroutines are asleep - deadlock!。例如主协程从无缓冲 channel 收数据,但没有任何 goroutine 往里发:ch := make(chan int)
<-ch // 主协程永远阻塞,无其他 goroutine -> deadlock
- 用 select 的 default 分支做非阻塞收发:select { case v := <-ch: ... default: ... }
- 用 select + time.After / context 超时跳出等待:
select {
case v := <-ch:
fmt.Println(v)
case <-time.After(time.Second):
fmt.Println("timeout")
}
- 给 channel 加缓冲 make(chan int, n),让发送方先写入而不立即阻塞(但不能消除逻辑死锁)。
- 确保有 goroutine 负责关闭/写入,并遵循“谁发送谁关闭”、用 for range ch 在关闭后退出接收。
题目与答案就在本页;收藏、批注和错题重练在应用内