Go 的 select 实战:超时、非阻塞收发与优雅退出的三个套路
Go 的 select 实战:超时、非阻塞收发与优雅退出的三个套路
很多人学 Go 并发,select只会写「从多个 channel 里随便读一个」。但实战里select真正好用的是三个套路:给操作加超时、非阻塞地试探 channel、以及优雅关闭 goroutine。这三个不掌握,写出来的并发代码要么卡死,要么泄漏 goroutine。这篇一个一个过。
套路一:给 channel 操作加超时
朴素写法:直接从 channel 读,读不到就永远阻塞。
// 危险:worker 出问题没往 ch 写,这里会永久卡住funcwaitResult(ch<-chanint)int{return<-ch}生产环境这种代码就是定时炸弹——上游一旦不响应,这个 goroutine 就永远挂在这里,连带上游的资源也释放不掉。正确做法是用select配一个time.After:
import"time"funcwaitResult(ch<-chanint)(int,error){select{casev:=<-ch:returnv,nilcase<-time.After(2*time.Second):// 超过 2 秒没结果就返回错误,不再干等return0,fmt.Errorf("timeout waiting for result")}}time.After(d)返回一个 channel,d时间后会往里塞一个值。select会同时监听结果 channel 和这个定时 channel,哪个先来走哪个。
一个坑:time.After在超时前不会被 GC 回收。如果你在一个高频循环里用它,会短暂堆积大量 Timer。循环内的超时应改用time.NewTimer并手动Stop:
funcwaitResultLoop(ch<-chanint){timer:=time.NewTimer(2*time.Second)defertimer.Stop()// 用完及时释放,避免 Timer 堆积select{casev:=<-ch:fmt.Println(v)case<-timer.C:fmt.Println("timeout")}}套路二:非阻塞收发
有时你不想等,只想「试一下,能读就读,不能读就算了」。关键是给select加一个default分支——只要有default,select就永远不会阻塞。
// 非阻塞读:channel 里有数据就拿,没有就走 defaultfunctryRead(ch<-chanint){select{casev:=<-ch:fmt.Println("got:",v)default:fmt.Println("nothing ready, skip")}}// 非阻塞写:channel 满了就丢弃,不阻塞生产者functrySend(chchan<-int,vint)bool{select{casech<-v:returntruedefault:returnfalse// 缓冲满了,主动丢弃(比如做限流/降级)}}非阻塞写在实战里特别有用:比如做一个「有界的事件上报队列」,队列满了宁可丢事件也不能阻塞主流程,trySend就是标准写法。
套路三:优雅退出 goroutine
启动了 goroutine 却没法通知它退出,是 Go 里最常见的泄漏源。标准解法是用一个donechannel(或context)配select:
funcworker(jobs<-chanint,done<-chanstruct{}){for{select{casejob:=<-jobs:process(job)case<-done:// 收到退出信号,清理后返回,goroutine 正常结束fmt.Println("worker exiting")return}}}funcmain(){jobs:=make(chanint)done:=make(chanstruct{})goworker(jobs,done)jobs<-1jobs<-2close(done)// 关闭 done,所有监听它的 select 都会立刻收到零值time.Sleep(100*time.Millisecond)// 等 worker 打印退出(实际用 WaitGroup)}funcprocess(nint){fmt.Println("processing",n)}这里的精髓是close(done)而不是往里发值:关闭 channel 后,所有从它读取的select分支都会立刻返回(读到零值),所以能一次性通知任意数量的 goroutine 退出,不用给每个 goroutine 单独发信号。
实际项目里更推荐直接用context.Context,它就是把这套donechannel 封装好了,还能级联取消:
funcworker(ctx context.Context,jobs<-chanint){for{select{casejob:=<-jobs:process(job)case<-ctx.Done():return// ctx 被 cancel 或超时,退出}}}小结
- 超时:
select+time.After,别裸读 channel;循环里改用time.NewTimer+Stop避免 Timer 堆积。 - 非阻塞:加
default分支,select就永不阻塞,适合做「能读就读、队满就丢」的降级逻辑。 - 优雅退出:
select监听done/ctx.Done(),用close(done)一次性通知所有 goroutine 退出,避免泄漏。
一句话记忆:select不只是「多路复用」,time.After、default、done三个搭配才是它在生产环境的真正价值——分别对应「不干等」「不阻塞」「能收场」。
