Select waits on multiple channels. This can be combined with goroutines. select is like the switch statement, but for channels.

If multiple channels need to be finished before moving on to the next step, select is what you need.

Example

Goroutines

Two goroutines are started concurrently. Each routine loops forever and writes data into a channel.

To be explicit: goroutine f1 writes data into channel c1 forever, goroutine f2 writes dat ainto channel c2 forever. The goroutines are simply like this:


func f1(c chan string) {
    for {
      time.Sleep(1 * time.Second)
       c <- "1"
    }
}

Select

Because it runs concurrently, it may happen that one task finishes before the other.

The select statement will make the program wait for both tasks to be completed, but that doesn’t mean both tasks are always finished in chronological order.


package main

import "fmt"
import "time"

func f1(c chan string) {
    for {
      time.Sleep(1 * time.Second)
       c <- "1"
    }
}

func f2(c chan string) {
    for {
      time.Sleep(1 * time.Second)
      c <- "2"
    }
}

func main() {
   c1 := make(chan string)
   c2 := make(chan string)

   go f1(c1)
   go f2(c2)

   for {
       select {
           case msg1 := <- c1:
               fmt.Println(msg1)
           case msg2 := <- c2:
               fmt.Println(msg2)
       }
   }
   fmt.Println("Goroutines finished.")
}
    $ go run example.go
    1
    2
    1
    2
    2
    1