Select Picks Ready Channels Randomly

Both sides stay ready throughout the loop, so select picks a case by uniform pseudo-random choice and the win counts vary across runs.

GoResilience

Code

gosnippet
30 lines
package main

import "fmt"

func main() {
	left := make(chan int, 8)
	right := make(chan int, 8)
	for i := 0; i < 8; i++ {
		left <- i
		right <- 100 + i
	}

	// 两个通道都有就绪值:Go 规范规定 select 用伪随机 (uniform pseudo-random)
	// 地选择一个可通信分支,而不是按书写顺序,避免饿死写在后面的分支
	leftWins, rightWins := 0, 0
	for i := 0; i < 6; i++ {
		select {
		case <-left:
			leftWins++
		case <-right:
			rightWins++
		}
	}
	fmt.Println("left wins:", leftWins)
	fmt.Println("right wins:", rightWins)

	// 只取 6 次、每侧缓冲 8 个值:两侧在整个循环里始终就绪,每次选择
	// 都是纯伪随机,胜出分配随运行变化(计数之和恒为 6、剩余之和恒为 2)
	fmt.Println("left remaining:", len(left), "| right remaining:", len(right))
}

What the code does

What another module actually calls is the function main — everything else is wiring.

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

Watch out for

  • The dependency list is empty — the language runtime already provides everything.

Applying it

The primary signature, spelled out, is func main()

Look for the left wins:, right wins:, left remaining: prefixes as the file executes; they connect every printed line to the step behind it.

Statements that matter most here

right := make(chan int, 8)
left := make(chan int, 8)
right <- 100 + i

Interactive Tools for This Topic

FAQ

What does Select Picks Ready Channels Randomly print when run?
Invoke the file as-is — the `left wins:`, `right wins:`, `left remaining:` prefixes identify which step printed each line.