Two-Stage Select Prefers A Priority Channel

A two-stage select drains the priority channel non-blocking first, then blocks on both channels, so urgent messages never wait behind bulk traffic.

GoResilience

Code

gosnippet
28 lines
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)
		}
	}
}

How it works

Two-Stage Select Prefers A Priority Channel reduces to the function main.

Repetition is confined to for delivered := 0; delivered < 4; delivered++ — the rest of the file is straight-line.

Using it

The demo output is labeled (high:, low:), so every line in the printed output names the step that produced it.

Key statements

high := make(chan string, 2)
low := make(chan string, 2)
high <- "timeout"

Interactive Tools for This Topic

FAQ

What does Two-Stage Select Prefers A Priority Channel print when run?
The script runs standalone; its 2 labeled outputs include `high:`, `low:`.