
5 Concurrency in Go
This chapter covers
- Viewing Go’s concurrency model
- Using goroutines for concurrent processing and communication
- Locking data and awaiting responses
- Using channels for intercoroutine communication
- Strategically closing channels
This chapter presents Go’s approach to and implementation of concurrency. Unlike many recent procedural and object-oriented languages, Go doesn’t provide a threading model for concurrency. Instead, it uses the concept of event-style goroutines and channels for communication between them. Concurrency is cheap (resource-wise) and much easier to manage than traditional thread pools. This chapter first focuses on goroutines, which are functions capable of running concurrently. Then it dives into channels, Go’s mechanism for handling communicating between goroutines. We’ll also look at mutexes, which are synchronization primitives that enable locking of resources as a way of enforcing consistency in concurrent systems.
5.1 Understanding Go’s concurrency model
Roughly speaking, concurrency is a program’s ability to do multiple things at the same time. In practice, when we talk about concurrent programs, we mean programs that have two or more tasks that run independently, at about the same time, but remain part of the same program.