9 Programming with channels
This chapter covers
- Introducing communicating sequential processes (CSP)
- Reusing common channel patterns
- Taking advantage of channels being first-class objects
Working with channels requires a different way to program than using memory sharing. The idea is to have a set of goroutines each with its own internal state, exchanging information with other goroutines by passing messages on Go’s channels. In this way, each goroutine’s state is isolated from direct interference of other executions, reducing the risk of race conditions.
Go’s own mantra is not to communicate by shared memory but to instead share memory by communicating. Since memory sharing is more prone to race conditions and requires complex synchronization techniques, when possible we should avoid it and instead use message passing.
In this chapter, we will start by discussing communicating sequential processes (CSP) and then move on to see the common patterns used when programming using message passing with channels. We finish this chapter by demonstrating the value of treating channels as first-class objects, meaning we can pass channels as function arguments and receive them back as function return types.