4 Synchronization with mutexes

 

This chapter covers

  • Protecting critical sections with mutex locks
  • Improving performance with readers–writer locks
  • Implementing a read-preferred readers–writer lock

We can protect critical sections of our code with mutexes so that only one goroutine at a time accesses a shared resource. In this way, we eliminate race conditions. Variations on mutexes, sometimes called locks, are used in every language that supports concurrent programming. In this chapter, we’ll start by looking at the functionality that mutexes provide. Then we’ll look at a variation on mutexes called readerswriter mutexes.

Readers–writer mutexes give us performance optimizations in situations where we need to block concurrency only when modifying the shared resource. They give us the ability to perform multiple concurrent reads on shared resources while still allowing us to exclusively lock write access. We will see a sample application of readers–writer mutexes, and we’ll learn about its internals and build one ourselves.

4.1 Protecting critical sections with mutexes

4.1.1 How do we use mutexes?

4.1.2 Mutexes and sequential processing

4.1.3 Non-blocking mutex locks

4.2 Improving performance with readers–writer mutexes

4.3 Exercises