实现说明
两段式 select 的优先级通道以函数 main为骨架。
for delivered := 0; delivered < 4; delivered++ 反复执行,循环体之外没有别的重复。
使用要点
- 演示输出是带标签的(
high:、low:),每个操作都会留下自己的一行标注。
常见问题
运行「两段式 select 的优先级通道」会打印什么?
文件本身就是完整程序,直接运行——输出行带有 high:、low: 这类标签。
核心语句
high := make(chan string, 2)
low := make(chan string, 2)
high <- "timeout"
代码示例
package main
import "fmt"
func main() {
high := make(chan string, 2)
low := make(chan string, 2)
high <- "alert"
high <- "timeout"
low <- "metric"
low <- "trace"
// Two-stage select: the first stage drains the high-priority channel without blocking, the second waits on both
for delivered := 0; delivered < 4; delivered++ {
select {
case v := <-high:
fmt.Println("high:", v)
continue
default:
}
select {
case v := <-high:
fmt.Println("high:", v)
case v := <-low:
fmt.Println("low:", v)
}
}
}