Mahdi.Kh
November 23, 2026
We learn how one goroutine can wait on several channels at once, add timeouts and non-blocking sends, and write a for-select loop that always knows how to stop.
Some goroutines have more than one thing to listen to. A chat client waits for messages from the server and for the user typing; a worker waits for its next job and for the signal to shut down; a request handler waits for the database, but not forever. With what we have so far, a goroutine can wait on only one channel at a time: while it is blocked on <-jobs, the shutdown signal can knock all it likes.
select fixes that. In this part we let one goroutine listen to several channels, add timeouts and operations that never wait, write the for-select loop that nearly every long-running goroutine in Go is built on, and look at the small traps hidden in it. It builds directly on the previous part about channels.
select looks like a switch, but every case is a channel operation, a receive or a send. It blocks until at least one case can go ahead, then runs exactly one of them. If several are ready at the same moment, it picks one at random, so no channel can starve the others. And if it has a default case, it never blocks: when nothing is ready, it runs default instead.
Picture a hotel receptionist with three phone lines. They don't stare at line one waiting for it to ring; they answer whichever line rings. If two ring at once they pick one, and the other keeps ringing until they are free again.
In the diagram above only emails has something to deliver, so select runs its case and the goroutine handles the email. The chats and ctx.Done() cases are not ready; they don't run, and nothing is taken from those channels. Once one case has run, the select is over. To keep listening you put it in a loop, which is what we do next.
Chats arrive every 100 ms and emails every 150 ms. One loop handles both, in whatever order they come:
Each turn of the loop waits until either channel has a message and handles that one. The messages come out in time order, interleaved, and the goroutine is never stuck on a quiet channel while the other one has something to say. At 300 ms an email and a chat are ready at the same moment, and select picks one at random, so the last two lines swap places from run to run.
main knows that exactly five messages are coming, so the producers don't close their channels. That is a crutch; we drop it in the sensors example below, and the mistakes section shows why closing changes things for select.
Waiting is fine; waiting forever is not. time.After(d) returns a channel that delivers a value once d has passed, so a timeout is simply one more case:
ask waits for whichever comes first, the forecast or 200 ms. The fast call answers in time; the slow one is abandoned, and the caller gets an error it can check with errors.Is. Look at the comment on make(chan string, 1), though. When we give up, the forecast goroutine is still sleeping. When it wakes up, it sends an answer that nobody will ever receive. On an unbuffered channel that send would block forever, one leaked goroutine per timeout; the one-slot buffer lets it drop the answer in and finish.
time.After creates a new timer each time it is evaluated, and in a loop the cases of a select are evaluated on every turn. That changes what the timeout means:
The first loop gives up after a second of silence, because each message starts a fresh one-second timer. That is an idle timeout, and with a steady trickle of messages it never fires. If you meant "this whole job must finish within five seconds", create the timer once before the loop, as in the second form, or use context.WithTimeout and wait on ctx.Done(). For an idle timeout in a busy loop you can also keep one timer and call Reset after each message instead of allocating a new one. Since Go 1.23, Reset and Stop guarantee that no stale value arrives afterwards, so the old ritual of draining the channel before Reset is no longer needed. (The time package post covers timers and tickers themselves.)
A default case turns select into an operation that never blocks: try to send or receive, and if that would wait, do something else. A classic use is a producer that must never be slowed down, such as code that records metrics on a request's hot path. When the buffer is full, it drops the event and counts it, instead of making the request wait:
The consumer stores one event every 50 ms while a new one arrives every 10 ms, so the three-slot buffer fills up and some events are dropped. Which ones, and how many, changes between runs, because it depends on who gets there first. Whether dropping is acceptable is a design decision: fine for metrics or progress updates, not for payments. The same shape works for receiving, too: select with a receive case and an empty default checks for a value without waiting.
Put a select inside a for and you have the backbone of most long-running goroutines: handle whatever arrives, and stop when told to. Here a dashboard merges readings from two sensors until both have finished, with a context as the emergency brake:
Three things make this loop trustworthy:
ctx.Done() case: the loop in main, and both waits inside the sensor goroutine, for the next tick and for someone to take the reading. Leave it out of any one of them, and cancelling could leave that goroutine stuck.r, ok := <-temp reports ok == false. main then sets temp = nil. A receive from a nil channel never goes ahead, so from then on select simply ignores that case and the loop carries on with the wind sensor alone. Once both are nil, the loop condition ends it.ctx.Done() and return as well, and nothing is left behind.This is the forecast from the timeout example with an unbuffered channel. Every call that times out leaves one goroutine blocked forever on its send, and a busy server leaks them by the thousand. Give the channel a buffer of one, as our program did, or let the sender select on ctx.Done() as well, so that it can give up too.
A closed channel is always ready. Had every in the first example closed its channel when it was done, as a good producer should, the loop would have received an empty string from emails at 300 ms and printed inbox: with nothing after it. In a loop with no fixed end it would spin, receiving zero values as fast as the CPU allows. Receive with v, ok := <-ch and set the channel to nil once ok is false, as the sensors loop does.
break inside a select ends the select, not the for around it. Here that also walks straight into the previous trap: jobs is closed, so the next select picks it again at once, forever. Use return, or a labeled break: put loop: before the for and write break loop.
A default in a for-select with nothing else to do turns waiting into a busy loop that burns a whole CPU core. Leave default out and let select block; that is what it is good at. Keep default for a single attempt that must not wait, like the dropped events above.
select has no priorities: when several cases are ready, each is equally likely. A worker whose jobs channel always has something waiting may run a few more jobs after its context is cancelled, before it happens to pick ctx.Done(). Usually that is fine. When it is not, check for cancellation first, in a select of its own with a default:
default to try a send or a receive without waiting.ctx.Done() case, so the goroutine can always be stopped.for range says the same thing more simply.select returns on the first ready case, and waiting for every goroutine is the job of WaitGroup.time.After around.select waits until one of its cases can go ahead and runs exactly one; among several ready cases it picks at random.time.After inside a loop restarts on every turn, so create the timer once for an overall deadline.default makes select non-blocking; never use it to poll in a loop.ctx.Done() case, and set channels to nil once they are closed.With goroutines, channels and select in hand, the next part starts on the patterns themselves with the pipeline: a chain of stages connected by channels.
Previous part: Channel Fundamentals | Concurrency in Go
Next part: Pipeline Pattern | Concurrency in Go