← Lessons

quiz vs the machine

Gold1440

Concurrency

Select and Timeout

Wait on many channels at once, but never wait forever.

4 min read · core · beat Gold to climb

Waiting on multiple channels

A select lets a process block on several channel operations at once and proceed with whichever becomes ready first. It is the channel world version of waiting on many events without busy looping.

How select chooses

  • If one operation is ready, that one runs.
  • If several are ready, one is chosen, often at random to avoid starving any case.
  • If none is ready, select blocks until one becomes ready.

The random choice matters: always picking the first ready case could let one busy channel monopolize the loop.

Adding a timeout

A timeout is just another channel that becomes ready after a delay. Put it in the select and you get a bounded wait: either real work arrives, or the timeout fires and you take a fallback path.

Non blocking attempts

A select with a default case never blocks: if nothing is ready, the default runs immediately. This turns a blocking receive into a polite try and move on.

Key idea

Select waits on many channel operations and runs whichever is ready first, and a timeout channel turns an unbounded wait into a bounded one.

Check yourself

Answer to earn rating on the learn ladder.

1. When several cases in a select are ready at once, what typically happens?

2. How is a timeout implemented in a select?