A loop spins on the processor while it waits, with an empty body or a select whose default does nothing

tx0/go:busy-waitrecommendedwarningbug, concurrency, performance

What it finds

for !done {} or for { select { case <-ch: ...; default: } }: the loop checks again and again without ever blocking, so it keeps a processor busy while it waits, and a condition that another goroutine sets without synchronization may never be seen at all. A channel receive, a sync.WaitGroup or a condition variable blocks until there is something to do.

Reported are for loops without a range or post statement whose body is empty and has no comment, unless the condition calls a function or receives, which can do the work of the loop, as in for processNext() {}, and for loops whose body is only a select with an empty default case.

From the rule's source, busy_wait.rs.

Example from the rule's tests
package p func f(done *bool, ch chan int, quit chan struct{}) int {	for !*done {}tx0 reports: this loop spins with an empty body while it waits	for {		select { case v := <-ch: return v; default: }tx0 reports: the empty default makes this loop spin while it waits	}} func g(ch chan int, quit chan struct{}) {	for {		select {		case <-ch:		case <-quit:			return		}	}} func h(ch chan int, ready *bool) int {	for i := 0; i < 10; i++ {}	for !*ready {		// Polling is fine here: the flag is set right after start.	}	for processNext() {}	for {		select {		case v := <-ch:			return v		default:			work()		}	}} func processNext() bool { return false } func work() {}
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

Turn it on, off or suppress it

The rule runs from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:

tx0.toml
[rules]
"tx0/go:busy-wait" = "warning"

To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:

// tx0: ignore[tx0/go:busy-wait] reason="..."

tx0 explain tx0/go:busy-wait shows the same in the terminal. Found a false positive? Report it.