liveBook · Manning

Uniform pseudo-random selection

As explained in 100 Go Mistakes and How to Avoid Them

Uniform pseudo-random selection is a selection process that chooses among eligible alternatives with equal pseudo-random probability.

A common mistake is treating select cases like switch cases: source order does not establish priority. When multiple channel communications can proceed, Go chooses one through uniform pseudo-random selection, so execution is nondeterministic. section 9.4

Buffered channels can stop early

A loop selecting between messageCh and disconnectCh may receive only 0, 5, or 10 messages before returning. If both channels are ready, the first case is not guaranteed to win; random selection prevents starvation that fixed source-order priority could cause. section 9.4

Choose a contextual fix when disconnection must follow every message:

  • Use an unbuffered message channel when a single producer must block until each message is received. section 9.4
  • Use one channel carrying either a message or a disconnection notification. section 9.4

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Defines readiness-based selection, demonstrates nondeterministic output, and stops short of deeper random-number implementation details.
Examples
Uses competing message and disconnection channels, ten produced messages, variable output, and a nested draining select.
What you can do after
Diagnose nondeterministic select behavior and choose channel designs or draining logic that preserve required message handling.
How it connects
Connects select statements with channels, buffering, starvation, and unbuffered synchronization.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.