Waiting on several channels

Sometimes a goroutine waits for values from more than one channel, and it cannot know which will be ready first. If it writes <-a and then <-b, it waits for a even when b already has a value. The select statement solves this. It waits on several channel operations at once and runs the first one that is ready.

package main

import (
	"fmt"
	"time"
)

func sendAfter(ch chan string, msg string,
	ms int) {
	time.Sleep(time.Duration(ms) * time.Millisecond)
	ch <- msg
}

func main() {
	fast := make(chan string)
	slow := make(chan string)
	go sendAfter(fast, "fast", 10)
	go sendAfter(slow, "slow", 50)

	select {
	case msg := <-fast:
		fmt.Println("got", msg)
	case msg := <-slow:
		fmt.Println("got", msg)
	}
}

Output:

got fast

select looks like switch, but each case is a channel operation. The fast message arrived after 10 milliseconds, so its case ran. The other case was skipped, and select ended.

time.Millisecond is a value of type time.Duration. ms is a plain int, so time.Duration(ms) converts it before the multiplication.

Waiting for both

One select handles one message. To get both, put the select in a loop:

fast := make(chan string)
slow := make(chan string)
go func() {
	time.Sleep(50 * time.Millisecond)
	slow <- "slow"
}()
go func() {
	time.Sleep(10 * time.Millisecond)
	fast <- "fast"
}()

for i := 0; i < 2; i++ {
	select {
	case msg := <-fast:
		fmt.Println(msg)
	case msg := <-slow:
		fmt.Println(msg)
	}
}

Output:

fast
slow

Timeouts

time.After returns a channel that receives a value after the given time. Put it in a select, and you have a timeout: a limit on how long to wait.

results := make(chan string)
go func() {
	time.Sleep(200 * time.Millisecond)
	results <- "done"
}()

select {
case r := <-results:
	fmt.Println(r)
case <-time.After(50 * time.Millisecond):
	fmt.Println("timeout")
}

Output:

timeout

The work needed 200 milliseconds, but the program waited only 50. case <-time.After(...) receives a value and throws it away, because only the moment it arrives matters. Programs that call other servers use timeouts like this so they do not wait forever.

Not waiting at all

A default case runs when no other case is ready. Then select does not wait at all:

messages := make(chan string)

select {
case m := <-messages:
	fmt.Println(m)
default:
	fmt.Println("no message yet")
}

Output:

no message yet

When two cases are ready

If several cases are ready at the same moment, Go picks one of them at random. It does not prefer the first case. So do not count on the order of the cases. In our examples, the delays are far apart, so one message is always clearly first.

In the exercise, finish the select: print whichever message arrives first, or timeout if neither arrives within 100 milliseconds.