Go Select — 多路复用选择
用 select 同时监听多个 channel,超时控制 · 难度:高级 · +20XP
select — 等待多个 channel
select 让你同时等待多个 channel,哪个先有数据就处理哪个。类似于操作系统的 select/poll,但语法极简。
基本用法
ch1 := make(chan string)
ch2 := make(chan string)
go func() { time.Sleep(1*time.Second); ch1 <- "one" }()
go func() { time.Sleep(2*time.Second); ch2 <- "two" }()
for i := 0; i < 2; i++ {
select {
case msg1 := <-ch1: fmt.Println("收到:", msg1)
case msg2 := <-ch2: fmt.Println("收到:", msg2)
}
}
超时控制
select {
case res := <-ch:
fmt.Println(res)
case <-time.After(3 * time.Second):
fmt.Println("超时!3秒未响应")
}