Concurrency is dealing with a lot of things at once. Parallelism is doing a lot of things at once. —Rob Pike, from his Waza talk (https://go.dev/blog/waza-talk)
Concurrency may involve parallelism, but these two concepts are not the same. Concurrency is about structuring the code, whereas parallelism is about executing the code simultaneously.
Many goroutines can run concurrently on a single CPU through context switching, whereas parallelism may occur when multiple CPUs execute goroutines simultaneously. Grasping this distinction helps us structure concurrent code regardless of the number of available CPUs.
In this appendix, we’ll explore goroutines and channels. This appendix builds on concepts introduced in chapter 1; it’s a good idea to review that chapter to understand those concepts fully. Throughout the appendix, we may omit package
and import
declarations from listings to save space and trees. Listings can also omit the work
function after we declare it in section E.1.1. In any case, assume that the package is main
and the work
function is declared.
E.1 Goroutines
Goroutines are lightweight, independently running concurrent functions. They can handle multiple tasks concurrently without the overhead of traditional threads. We’ll examine how to start a goroutine and see the differences between running sequential and concurrent code.