goroutine 阻塞主因是 channel 使用不当或 select 缺少 default 分支,导致死锁;无缓冲 channel 发送时若无接收方会永久阻塞,引发“all goroutines are asleep”错误。
goroutine 阻塞通常不是因为“太多 goroutine”,而是 channel 使用不当或 select 缺少默认分支导致的死锁或资源滞留。Go 运行时不会主动回收卡在无缓冲 channel 发送/接收上的 goroutine,必须靠设计规避。

向无缓冲 channel 发送数据,若没有 goroutine 同时执行接收,发送方会一直阻塞 —— 这是最常见的死锁源头。
常见错误现象:fatal error: all goroutines are asleep - deadlock!
ch := make(chan int) 执行 ch ,除非另起 goroutine 接收
ch := make(chan int, 1),允许一次未匹配的发送select + default 实现非阻塞尝试select 在所有 case 都不可达时会阻塞,若没写 default,就等同于“等待任意 channel 就绪”——但若所有 channel 永远不就绪,goroutine 就挂住了。
使用场景:轮询多个 channel、实现超时、避免单点阻塞
default,哪怕只写 default: continue
time.After 或 time.NewTimer 配合 case
select 里重复读同一 channel 多次(如两个 case ),Go 不保证执行顺序,且可能漏消息
select {
case v := <-ch:
fmt.Println("received", v)
default:
fmt.Println("no message, moving on")
}向已关闭的 channel 发送会 panic:panic: send on closed channel;从已关闭的 channel 接收会立即返回零值 + false(ok 为 false),但若忽略 ok 判断,逻辑可能出错。
参数差异:v, ok := 中 ok 是关键信号,而 v := 会静默吞掉关闭状态
v, ok := 判断是否关闭,尤其在 for 循环中
长期运行的 goroutine(如监听 loop)若没收到退出信号,会持续占用内存和栈空间,表现为 goroutine 数量随时间增长。
性能影响:泄漏的 goroutine 不仅吃内存,还增加调度器负担,尤其在高并发服务中易被压垮
ctx.Done() 或自定义 done chan struct{}
go func() {
defer close(output)
for {
select {
case <-ctx.Done():
return
case item := <-input:
output <- process(item)
}
}
}()runtime.NumGoroutine() 快速验证是否存在意外残留最易被忽略的是:把 channel 当作队列用却忘了容量限制,或在 select 中依赖“某个 case 必然发生”——而实际它可能永远不发生。阻塞不是 Go 的 bug,是并发契约没写清楚的体现。