Ready-case selection and fairness
Ready-case selection and fairness
When several communications can proceed, Go select chooses one by uniform pseudo-random selection. Source order does not assign priority, and the rule does not promise that a particular case wins within a fixed number of iterations. Avoid tests that expect a specific winner.
package main
import ( "fmt")
func main() { a := make(chan int, 1) b := make(chan int, 1) a <- 1 b <- 2 v := 0 select { case v = <-a: case v = <-b: } fmt.Println(v == 1 || v == 2, len(a)+len(b))}Both are ready, so either 1 or 2 is valid. The test checks that one value was consumed instead of checking which. A cancellation signal can also compete with ready work; placing it first is not a priority mechanism.
Expected output:
true 1Check an already signaled stop before work
package main
import ( "fmt")
func next(stop <-chan struct{}, jobs <-chan int) (int, bool) { select { case <-stop: return 0, false default: } select { case <-stop: return 0, false case v, ok := <-jobs: return v, ok }}func main() { stop := make(chan struct{}) jobs := make(chan int, 1) jobs <- 9 close(stop) fmt.Println(next(stop, jobs)) fmt.Println(len(jobs))}The preliminary nonblocking check rejects work if stop is already closed at that check. If stop closes afterward, both operations in the second select may still be ready. This is cooperative cancellation, not atomic priority or a strict guarantee that no work starts after cancellation.
Expected output:
0 false1Try it locally
Fill two capacity-one channels with 4 and 6, then perform two select receives. Print the sum, without assuming the order.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Select and cancellation 04: Ready-case selection and fairness
Check the lesson objective before moving on.
If two receives are ready, which wins?
Does a preliminary stop check guarantee no work after a later cancellation?