Skip to content
Codewilds

Lesson 35 of 38 · Concurrency

Go select: Timeouts and Non-blocking Channels

hard30 XP3 min read

A goroutine often has to wait for more than one thing: a result or a timeout, new work or a signal to stop. A plain receive can only wait on one channel. Go's select statement waits on several channel operations at once and runs whichever is ready first.

Waiting on several channels

select looks like a switch, but every case is a send or a receive:

package main

import (
	"fmt"
	"time"
)

func main() {
	hare := make(chan string)
	tortoise := make(chan string)
	go func() {
		time.Sleep(50 * time.Millisecond)
		tortoise <- "tortoise"
	}()
	go func() {
		time.Sleep(5 * time.Millisecond)
		hare <- "hare"
	}()

	select {
	case winner := <-hare:
		fmt.Println("first:", winner)
	case winner := <-tortoise:
		fmt.Println("first:", winner)
	}
}
first: hare

select blocks until one of its cases can proceed, runs that one case and is done. If several cases are ready at the same moment, Go picks one at random, so no channel can starve the others — the order in which you write the cases doesn't matter.

Timeouts with time.After

time.After(d) returns a channel that delivers a value once the duration d has passed. As a select case, it limits how long you wait:

select {
case res := <-results:
	fmt.Println("got", res)
case <-time.After(100 * time.Millisecond):
	fmt.Println("timed out")
}

If no result arrives within 100 ms, the timeout case wins. This is how Go programs avoid hanging forever on a slow server or a stuck worker.

Non-blocking operations with default

A default case runs immediately when no other case is ready, which turns a blocking operation into a non-blocking one:

msgs := make(chan string, 1)

select {
case m := <-msgs:
	fmt.Println("received", m)
default:
	fmt.Println("no message")
}

select {
case msgs <- "hi":
	fmt.Println("sent")
default:
	fmt.Println("buffer full, message dropped")
}
no message
sent

A receive case can use the comma-ok form as well: in case v, ok := <-ch:, ok is false when the channel is closed.

Stopping a loop with a done channel

A for loop around a select is the typical shape of a long-running goroutine. A done channel tells it when to stop:

func worker(jobs <-chan int, done <-chan struct{}) {
	for {
		select {
		case j := <-jobs:
			fmt.Println("working on", j)
		case <-done:
			fmt.Println("stopping")
			return
		}
	}
}

struct{} is the empty struct type: a chan struct{} carries no data, it only signals. The owner calls close(done), and because a receive from a closed channel succeeds immediately, every goroutine waiting on done wakes up — closing a channel is a broadcast. The standard context package is built on exactly this idea.

Common mistakes

  • default in a busy loop: the loop never blocks and burns CPU while it waits. Use default for one-off checks.
  • Ignoring ok on a channel that may be closed: a closed channel is always ready, so the case fires again and again with zero values.
  • Expecting the first case to win: when several cases are ready, the choice is random.
  • time.After inside a loop when you mean one overall deadline: every iteration starts a fresh timer. Create it once, before the loop.

Assignment

Write four functions, each built around select:

  1. TryReceive(ch <-chan int) (int, bool) never blocks. If a value is waiting, it returns the value and true; if no value is ready or ch is closed, it returns 0, false.
  2. FirstOf(a, b <-chan string) string waits until either channel delivers a value and returns that value.
  3. ReceiveWithTimeout(ch <-chan int, d time.Duration) (int, error) returns the next value from ch and nil, or 0 and ErrTimeout if nothing arrives within d. ErrTimeout is already declared in the starter.
  4. SumUntil(in <-chan int, done <-chan struct{}) int adds up the values received from in until in is closed or done is closed, then returns the sum.
ch := make(chan int, 1)
TryReceive(ch) // 0 false
ch <- 7
TryReceive(ch) // 7 true

Premium lesson

Unlock the full Learn Go course

  • All 38 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 9 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.

Keep learning

Need a quick reminder? The Go cheat sheet has every topic of Learn Go on one page.

Lesson last updated on .

Write code ↓
Go+30 XP

Lesson 35 is part of the full course. The first 9 lessons are free.

Premium lesson

Unlock the full Learn Go course

  • All 38 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 9 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.