8 Selecting channels

 

This chapter covers

  • Selecting from multiple channels
  • Disabling select cases
  • Choosing between message passing and memory sharing

In the previous chapter, we used channels to implement message passing between two goroutines. In this chapter, we will see how to use Go’s select statement to read and write messages on multiple channels and to implement timeouts and non-blocking channels. We will also examine a technique for excluding channels that have been closed and consuming only from the remaining open channels. Finally, we’ll discuss memory sharing versus message passing and when we should choose one technique over the other.

8.1 Combining multiple channels

How can we have one goroutine respond to messages coming from different goroutines over multiple channels? Go’s select statement lets us specify multiple channel operations as separate cases and then execute a case depending on which channel is ready.

8.1.1 Reading from multiple channels

Let’s think of a simple scenario where a goroutine is expecting messages from separate channels, but we don’t know on which channel the next message will be received. The select statement lets us group read operations on multiple channels together, blocking the goroutine until a message arrives on any one of the channels (see figure 8.1).

Figure 8.1 Select blocks until a channel becomes available.

8.1.2 Using select for non-blocking channel operations

8.2.1 Balancing code simplicity