chapter seven

7 Communication using message passing

 

This chapter covers

  • Exchanging messages for thread communication
  • Adopting Go’s channels for message passing
  • Collecting asynchronous results using channels
  • Building our own channels

So far, we have talked about having our goroutines solve problems by sharing memory and using synchronization controls to prevent them from stepping over each other. Message passing is another way to enable inter-thread communication (ITC), which is when goroutines send messages to or wait for messages from other goroutines.

In this chapter, we will explore using Go’s channels to send and receive messages among our goroutines. This chapter will serve as an introduction to programming concurrency using an abstraction that takes ideas from a formal language called communicating sequential processes (CSP). We’ll go into more detail about CSP in the following chapters.

7.1 Passing messages

Whenever we converse or communicate with friends, family, or colleagues, we do so by passing messages to each other. In speech, we say something and usually expect a reply or a reaction from whomever we’re speaking to. This expectation is also valid when we’re communicating by letter, email, or phone. Message passing between goroutines is similar. In Go, we can open a channel between two or more goroutines and then program the goroutines to send and receive messages among themselves (see figure 7.1).

Figure 7.1 Goroutines passing messages to each other

7.1.1 Passing messages with channels

7.1.2 Buffering messages with channels

7.1.3 Assigning a direction to channels

7.1.4 Closing channels

7.3 Exercises