Chapter 10. Concurrency in Go

Concurrency is the computer science term for breaking up a single process into independent components and specifying how these components safely share data. Most languages provide concurrency via a library that uses operating system–level threads that share data by attempting to acquire locks. Go is different. Its main concurrency model, arguably Go’s most famous feature, is based on CSP (Communicating Sequential Processes). It’s a style for concurrency that was described in 1978 in a paper by Tony Hoare, the man who invented the Quicksort algorithm. The patterns implemented with CSP are just as powerful as the standard ones, but are far easier to understand.

In this chapter, we are going to go through a quick review of the features that are the backbone of concurrency in Go: goroutines, channels, and the select keyword. Then we are going to look at some common Go concurrency patterns, and we will then learn about the situations where lower-level techniques are a better approach.

When to Use Concurrency

Let’s start with a word of caution. Be sure that your program benefits from concurrency. When new Go developers start experimenting with concurrency, they tend to go through a series of stages:

  1. This is amazing; I’m going to put everything in goroutines!

  2. My program isn’t any faster. I’m adding buffers to my channels.

  3. My channels are blocking and I’m getting deadlocks. I’m going to use buffered channels with really big buffers. ...

Get Learning Go now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.