select
# select
select 等待多个 Channel 操作,可组合结果、超时和取消信号。多个分支同时就绪时会选择其中一个执行。
timer := time.NewTimer(2 * time.Second)
defer timer.Stop()
select {
case value := <-results:
fmt.Println(value)
case <-timer.C:
return errors.New("timeout")
case <-ctx.Done():
return ctx.Err()
}
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
没有分支的 select {} 会永久阻塞;带 default 的 select 不会等待,循环中滥用会造成忙等。高频超时应显式管理 time.Timer,避免反复创建无法复用的计时器。