Overview
Use select with a default case in Go to add a job to a bounded queue without blocking, and report a full queue right away instead of freezing the caller.
- select runs the first ready case
- default runs when nothing is ready
- a send on a full channel blocks
Short Course
select waits on several channel operations and runs the first one that is
ready; a default case runs if none is. Trap: a plain send on a full channel
blocks until a reader makes room, so a busy queue freezes the caller.
select {
case msg := <-inbox:
handle(msg)
default:
// nothing waiting: carry on
}
Task
Write TryEnqueue(queue chan string, job string) bool: add job and return
true if there is room, otherwise return false at once. Example: on a queue
of capacity 1, the first call returns true and the second false.
Test Suites
Pending
Next
Output