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.