Select
, chan
Suppose we have one or more goroutines running, and they are sending the results of their computations over channels. We can use the select block to receive these results.
Though it is possible to use goroutines without select, this construct makes receiving values in a complicated program easier. We can use select within a for
-loop to receive all values.
This program uses 2 channels that send ints back (the chan
int
type is used). In the select statement, we receive the values sent from within those goroutines.
func
" keywords and receives an int
, and has 2 send statements where it sends values onto the first channel.for
-loop to loop infinitely until a break
keyword (found in the select default case) is reached.package main
import (
"fmt"
"time"
)
func main() {
// Part 1: make a couple channels that send ints.
c := make(chan int)
c2 := make(chan int)
// Part 2: use this goroutine to accept 1 argument and send 2 ints.
go func(x int) {
c <- 222 + x
c <- 500 + x
}(1)
// Part 3: use (and call) another goroutine that acts on the second channel.
go func(x int) {
c2 <- 555 + x
c2 <- 1000 + x
}(1)
// Part 4: sleep, as we need to be sure the goroutines have run.
time.Sleep(10000)
// Part 5: continue looping until no more channel activity.
for {
r := 0
// Part 6: use select to receive results from channels, and handle default case where nothing is happening.
select {
case r = <-c:
fmt.Println("RESULT FROM CHAN: ", r)
case r = <-c2:
fmt.Println("RESULT FROM CHAN2: ", r);
default:
fmt.Println("END")
return
}
}
}RESULT FROM CHAN2: 556
RESULT FROM CHAN: 223
RESULT FROM CHAN: 501
RESULT FROM CHAN2: 1001
END
The select statement is a critical component to using goroutines in the Go language. It makes receiving values from channels easier and we can merge all results with it.