Managing multiple operations

There are many situations in which more than one goroutines are executing their code and communicating through channels. A typical scenario is to wait for one of the channels' send or receive operations to be executed.

When you operate with many channels, Go makes it possible to use a special keyword that executes something similar to switch but for channel operations. This is done with the select statement, followed by a series of case statements and an optional default case.

We can see a quick example of where we are receiving a value from a channel in a goroutine, and sending a value to another channel in a different goroutine. In these, the main goroutine we are using is a select statement to interact with the two channels, receive from the first, and send to the second:

func main() {
ch1, ch2 := make(chan int), make(chan int)
a, b := 2, 10
go func() { <-ch1 }()
go func() { ch2 <- a }()
select {
case ch1 <- b:
fmt.Println("ch1 got a", b)
case v := <-ch2:
fmt.Println("ch2 got a", v)
}
}

The full example is available at https://play.golang.org/p/_8P1Edxe3o4.

When running this program in the playground, we can see that the receive operation from the second channel is always the first to finish. If we switch the execution order of the goroutines, we get the opposite results. The operation executed last is the one picked up first. This happens because the playground is a web service that runs and executes Go code in a safe environment and does some optimizations to make this operation deterministic.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.149.240.196