13. Synchronization

In Chapter 11, we explained how to use channels for passing data between goroutines. Then in Chapter 12, we discussed how to use the context1 package to manage the cancellation of goroutines. In this chapter, we cover the final part of concurrent programming: synchronization.

1. https://pkg.go.dev/context

We show you how to wait for a number of goroutines to finish. We explain race conditions,2 how to find them using Go’s -race3 flag, and how to fix them with sync.Mutex4 and sync.RWMutex.5

2. https://en.wikipedia.org/wiki/Race_condition

3. https://golang.org/doc/articles/race_detector

4. https://pkg.go.dev/sync#Mutex

5. https://pkg.go.dev/sync#RWMutex

Finally, we discuss how to use sync.Once to ensure a function is only executed ...

Get Go Fundamentals: Gopher Guides 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.