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 {
.Sleep(1 * time.Second)
time<- "1"
c }
}
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 {
.Sleep(1 * time.Second)
time<- "1"
c }
}
func f2(c chan string) {
for {
.Sleep(1 * time.Second)
time<- "2"
c }
}
func main() {
:= make(chan string)
c1 := make(chan string)
c2
go f1(c1)
go f2(c2)
for {
select {
case msg1 := <- c1:
.Println(msg1)
fmtcase msg2 := <- c2:
.Println(msg2)
fmt}
}
.Println("Goroutines finished.")
fmt}
$ go run example.go
1
2
1
2
2
1