Nonblocking select without busy looping
Nonblocking select without busy looping
A default branch makes select nonblocking: it runs only when no communication can proceed. This is useful for a one-time attempt, such as offering work to a bounded queue. A loop that repeatedly executes an empty default can consume CPU while achieving nothing.
package main
import ( "fmt")
func offer(q chan<- int, v int) bool { select { case q <- v: return true default: return false }}func main() { q := make(chan int, 1) fmt.Println(offer(q, 10), offer(q, 20)) fmt.Println(<-q)}The first offer fills the queue; the next returns false rather than waiting. The caller must decide whether to reject, retry later or report overload. This is a deliberate policy, not a guarantee that every job is processed. Do not use this helper after the queue owner closes q: sending to a closed channel can panic.
Expected output:
true false10Wait instead of polling
package main
import ( "fmt")
func main() { jobs := make(chan int) done := make(chan struct{}) go func() { defer close(done) for v := range jobs { fmt.Println(v) } }() jobs <- 3 close(jobs) <-done}The worker blocks in range while no jobs arrive, then finishes when jobs closes. No polling interval or sleep is needed. A blocking select is similarly appropriate when waiting on several sources. The done channel joins the worker before main returns.
Expected output:
3Try it locally
Write tryReceive(q <-chan int) (int, bool). For an open buffered queue containing 8, call twice and print each pair. Return zero,false if no value is ready; also return false on closure.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Select and cancellation 02: Nonblocking select without busy looping
Check the lesson objective before moving on.
When does default run?
What avoids busy polling when work may arrive later?