4 Synchronization with mutexes

 

This chapter covers

  • Protecting critical sections with mutex locks
  • Improving performance with readers-writer locks
  • Implementing a 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 of mutexes, sometimes called locks, are used in every language that supports concurrent programming. In this chapter we start by understanding the functionality that mutexes provide, then we look at a variation of mutexes called readers-writer mutexes.

Readers-writer mutexes give us a performance optimization in situations where we need to block concurrency only on modifying the shared resource. They give us the ability to perform multiple concurrent reads on our shared resources while still allowing us to exclusively lock write access. We will see a sample application for the readers-writer mutexes and in addition we will 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 lock

4.2 Improving performance with readers-writer mutexes

4.2.1 Go’s readers-writer mutex

4.2.2 Building our own readers-writer mutex

4.3 Summary

4.4 Exercises