liveBook · Manning

Busy-waiting loop

As explained in 100 Go Mistakes and How to Avoid Them

A busy loop is a repeated polling loop that continuously checks a condition instead of blocking until the condition may have changed.

A busy-waiting loop repeatedly checks a condition instead of blocking until it may change. It can produce the right result while wasting CPU cycles. section 9.12 section 9.6

type Donation struct {               #1
    mu             sync.RWMutex
    balance int
}
donation := &Donation{}
 
// Listener goroutines
f := func(goal int) {                #2
    donation.mu.RLock()
    for donation.balance < goal {    #3
        donation.mu.RUnlock()
        donation.mu.RLock()
    }
    fmt.Printf("$%d goal reached\n", donation.balance)
    donation.mu.RUnlock()
}
go f(10)
go f(15)
 
// Updater goroutine
go func() {
    for {                            #4
        time.Sleep(time.Second)
        donation.mu.Lock()
        donation.balance++
        donation.mu.Unlock()
    }
}()

Each donation listener repeatedly releases and reacquires a read lock while checking its goal. The mutex protects the balance, but the listeners consume CPU while waiting for the updater. section 9.12

For updates that multiple listeners must observe, use a condition variable to signal changes. A shared channel is not equivalent: each sent value is received by only one listener, so a listener can miss the update at its goal. section 9.12

type Donation struct {
    cond    *sync.Cond                    #1
    balance int
}
 
donation := &Donation{
    cond: sync.NewCond(&sync.Mutex{}),    #2
}
 
// Listener goroutines
f := func(goal int) {
    donation.cond.L.Lock()
    for donation.balance < goal {
        donation.cond.Wait()              #3
    }
    fmt.Printf("%d$ goal reached\n", donation.balance)
    donation.cond.L.Unlock()
}
go f(10)
go f(15)
 
// Updater goroutine
for {
    time.Sleep(time.Second)
    donation.cond.L.Lock()
    donation.balance++                    #4
    donation.cond.L.Unlock()
    donation.cond.Broadcast()             #5
}

Listeners wait on a sync.Cond and recheck the balance in a loop. The updater increments the balance and broadcasts an update to the listeners. The condition loop remains, but it no longer continuously polls. section 9.12

A select loop can also busy-wait without an explicit polling condition. A receive from a closed channel remains ready, so marking that channel closed with a Boolean does not prevent select from repeatedly choosing it while the other channel has no new value. section 9.6

func merge(ch1, ch2 <-chan int) <-chan int {
    ch := make(chan int, 1)
    ch1Closed := false
    ch2Closed := false
 
    go func() {
        for {
            select {
            case v, open := <-ch1:
                if !open {               #1
                    ch1Closed = true
                    break
                }
                ch <- v
            case v, open := <-ch2:
                if !open {               #2
                    ch2Closed = true
                    break
                }
                ch <- v
            }
 
            if ch1Closed && ch2Closed {  #3
                close(ch)
                return
            }
        }
    }()
 
    return ch
}

This merge tracks closure with Booleans, but leaves closed channels in the select. section 9.6

func merge(ch1, ch2 <-chan int) <-chan int {
    ch := make(chan int, 1)
 
    go func() {
        for ch1 != nil || ch2 != nil {    #1
            select {
            case v, open := <-ch1:
                if !open {
                    ch1 = nil             #2
                    break
                }
                ch <- v
            case v, open := <-ch2:
                if !open {
                    ch2 = nil             #3
                    break
                }
                ch <- v
            }
        }
        close(ch)
    }()
 
    return ch
}

This version assigns a closed input to nil. Its receive can no longer proceed, so select waits for the remaining input; the loop ends when both inputs are nil. section 9.6

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Traces both busy-wait mechanisms and contrasts them with condition-variable broadcast and nil-channel fixes.
Examples
Uses donation-goal listeners and a two-input channel merge to expose unnecessary looping.
What you can do after
Diagnose/debug polling and closed-channel loops, then replace them with blocking notification or nil-channel selection.
How it connects
Connects busy-waiting with mutexes, condition variables, channels, and select.

Also explained in

Compare how 3 books explain busy-waiting loop →

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.