select with default in Go
A default case makes select non-blocking, which is how you poll.
func poll(jobs chan int) string {
select {
case job := <-jobs:
return fmt.Sprintf("got %d", job)
default:
return "nothing waiting"
}
}
func trySend(jobs chan int, job int) bool {
select {
case jobs <- job:
return true
default:
return false // queue full, drop it
}
}
How it works
- Without default, select waits for a ready case.
- With default, it takes that branch immediately when nothing is ready.
- Ready cases are chosen at random, so no case starves.
Keywords and builtins used here
boolcasechandefaultfuncintreturnselectstring
The run, in numbers
- Lines
- 17
- Characters to type
- 267
- Tokens
- 60
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 36 seconds.
Step 2 of 3 in select, step 9 of 25 in Concurrency.