Select

Go’s select lets you wait on multiple channel operations. Combining goroutines and channels with select is a powerful feature of Go.
  1. package main
  2. import (
  3. "fmt"
  4. "time"
  5. )
  6. func main() {
  7. // For our example we’ll select across two channels.
  8. c1 := make(chan string)
  9. c2 := make(chan string)
  10. // Each channel will receive a value after some amount of time,
  11. // to simulate e.g. blocking RPC operations executing in concurrent goroutines.
  12. go func() {
  13. time.Sleep(1 * time.Second)
  14. c1 <- "one"
  15. }()
  16. go func() {
  17. time.Sleep(2 * time.Second)
  18. c2 <- "two"
  19. }()
  20. // We’ll use select to await both of these values simultaneously,
  21. // printing each one as it arrives.
  22. for i := 0; i < 2; i++ {
  23. select {
  24. case msg1 := <-c1:
  25. fmt.Println("received", msg1)
  26. case msg2 := <-c2:
  27. fmt.Println("received", msg2)
  28. }
  29. }
  30. }

We receive the values “one” and then “two” as expected.
Note that the total execution time is only ~2 seconds since both the 1 and 2 second Sleeps execute concurrently.

  1. received one
  2. received two

Timeouts