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:
-
This is amazing; Iâm going to put everything in goroutines!
-
My program isnât any faster. Iâm adding buffers to my channels.
-
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.