
Golang Rwmutex is a synchronization tool that allows for safe and efficient access to shared resources in a multi-threaded environment.
It's a lock that allows multiple readers to access a resource simultaneously, while preventing writers from accessing the resource until all readers have finished.
In Golang, Rwmutex is implemented as a struct that contains a mutex and a read-writer status.
Rwmutex is useful for scenarios where you need to read from a shared resource more frequently than you write to it.
For example, in a database application, multiple readers can access the database simultaneously, while a writer can only access the database when no readers are present.
This reduces the overhead of locking and unlocking the database, making the application more efficient.
How Sync.RWMutex Works
Sync.RWMutex is a synchronization mechanism that helps protect shared resources from concurrent access. It allows multiple readers to access the data simultaneously, while preventing writers from accessing the data while readers are still accessing it.
The key to Sync.RWMutex is the concept of a "writable-region" and a "readable-region". A writable-region is the code block enclosed by rwm.Lock() and rwm.Unlock() calls, where rwm is a Sync.RWMutex object. This ensures that only one thread can execute the code within this region at a time.
Here's a step-by-step breakdown of how Sync.RWMutex works:
- Atomically adds one to the readerCount.
- If the readCount updated in the previous step was less than zero, try acquiring the semaphore readerSem or wait if unsuccessful, until it succeeds.
This means that while multiple readers can access the data simultaneously, a writer will not be able to access the data while there are still active readers. This is achieved through the use of a semaphore, which is acquired by the writer when it needs to access the data.
See what others are reading: Golang Semaphore
Example Usage
To use a read-write mutex in Go, you need to understand the different methods available.
The rwm.Lock() and rwm.Unlock() methods can be used for both reading and writing, but this can lead to issues if you want to prevent certain objects from using them.
The rwm.RLocker() method can be used to restrict objects to only use the rwm.RLock() and rwm.RUnlock() methods, which can be useful for a stricter separation of roles.
You can use rwm.RLocker() to create a Locker instance that provides access to only the RLock() and RUnlock() methods, without granting access to the writer lock.
This can be achieved by wrapping rwm.RLock() and rwm.RUnlock() as Lock() and Unlock() methods, which are the only methods declared in the Locker interface.
By using rwm.RLocker(), you can ensure that certain objects can only read from the mutex, preventing them from acquiring the writer lock.
Benefits and Drawbacks
The benefits and drawbacks of using Go's RWMutex are worth exploring. Using RWMutex can improve performance when mostly reads are happening.
In scenarios where mostly writes are happening, Mutex is actually simpler to use. However, in mixed scenarios, it's recommended to test both Mutex and RWMutex.
RWMutex has a significant performance advantage when mostly reads are happening, making it a better choice in such cases. It's faster than Mutex in this scenario.
However, in cases with frequent calls to atomic.AddInt32, RWMutex can cause cache-contention, degrading performance. This is why the Go authors added sync.Map to Go1.9.
Here's a summary of the trade-offs between Mutex and RWMutex in different scenarios:
Why We Need Mutex
Mutex is a synchronization primitive that helps manage access to shared resources in a program.
In Go, mutexes are used to protect shared variables from concurrent access by multiple goroutines.
A mutex is essentially a lock that allows only one goroutine to access a shared resource at a time.
Mutexes are necessary in concurrent programming because they prevent data corruption and ensure that shared variables are accessed safely.
Without mutexes, multiple goroutines might try to write to a shared variable simultaneously, leading to unpredictable behavior and potential crashes.
In the context of the Go runtime, mutexes are used to protect internal data structures and ensure that the program runs smoothly even under heavy concurrent loads.
RWMutex Basics
RWMutex separates read and write locks, allowing multiple readers while excluding other writers.
This design reduces waiting in read-heavy cases, making it a great choice for scenarios where reads dominate, like a cache example where reads are more frequent than writes.
The writer takes exclusive access to shared data using the Lock method, which acquires a mutex and decreases readerCount to block upcoming readers.
Always match locks with unlocks to avoid deadlocks, as new readers will be blocked and existing readers will continue execution.
A semaphore is used to remember the current number of readers and block the writer, which will be unblocked when the last reader unlocks the mutex in the RUnlock method.
Why Upgradable Read-Write Locks?
In Go, even though guidelines suggest avoiding locks, building a Redis server for concurrent access often requires them for maximum performance. We fell back to locks in our Upstash Redis server implementation, and the standard Go library wasn't enough.
The standard Go library wasn't sufficient for our needs, so we had to look for alternative solutions. We were searching for ways to scale our locks, and two ideas came up: partitioning the locks and replacing the sync.Mutex with a sync.RWMutex.
A fresh viewpoint: Watermill Golang Sync
sync.RWMutex is the read-write lock in the Go library, which allows multiple readers to have the lock at the same time when there's no writer around. It ensures that there are no readers in the critical section when a single writer has the lock.
Our commands work in memory, making them quick and short under the lock. However, some commands, like SUNION, SDIFF, and ZDIFF, can take long due to their complexity, which depends on the size of the data.
These read operations are mostly okay, as other readers can still continue under RWMutex, while writers are blocked. But we realized another problem: commands like SUNIONSTORE, SDIFFSTORE, and ZDIFFSTORE need to get the write lock, which can take long and block both reads and writes.
Rwmutex Basics
RWMutex separates read and write locks, allowing multiple readers to access a resource simultaneously while preventing writers from interfering with each other.
In a read-heavy scenario, RWMutex reduces waiting by allowing readers to proceed while a writer is holding the lock.
The writer takes 10ms in this example, so some readers may run before the write completes, printing an empty string, while others will see "value1" after the write.
The RLock() method allows multiple readers, while the Lock() method is for writes, making it suitable for scenarios where reads dominate.
To avoid deadlocks, always match locks with unlocks.
The RWMutex in Go allows multiple readers to have the lock at the same time when there is no writer around, making it ideal for scenarios with many concurrent readers.
It also allows a single writer to have the lock, ensuring that there are no readers in the critical section.
In the Upstash Redis server implementation, RWMutex is used to guard the keyspace with locks, allowing multiple readers to access the keyspace while preventing writers from interfering with each other.
Recursive Read Locking
Recursive read locking is prohibited by RWMutex to ensure the lock eventually becomes available. This is because a blocked Lock call excludes new readers from acquiring the lock.
If a goroutine holds a RWMutex for reading and another goroutine might call Lock, no goroutine should expect to be able to acquire a read lock until the initial read lock is released.
RWMutex works in a way that if there is a pending writer, all attempts to call RLock will lock, even if a read lock has already been acquired.
Methods and Implementation
The implementation of a RWMutex in Go is quite fascinating. The API is actually a modification of the sync.RWMutex, which is trivial to implement. This is because the RLock method is simple, it just increments a reader count and sleeps for a writer to leave the critical section if necessary.
The Lock method gets the underlying w lock first, which prevents other writes from getting in. However, it doesn't affect reads yet. If we split this method into two, the first half is basically an UpgradeableRLock and the second part is UpgradeWLock. This means the second part upgrades the upgradable-read to write.
We need a bool to keep track if the lock is upgraded or not. This bool doesn't need to be guarded for concurrent access because we'll access it only under rw.w.Lock().
Here's a summary of the RWMutex methods:
The internals of sync.RWMutex involve a structure with a reader count and a semaphore for writers. Acquiring the lock involves atomically subtracting the maximum number of readers from the reader count, and if there are non-zero readers, adding the reader count to the reader wait. If the reader wait is non-zero, it tries to acquire the writer semaphore or waits until it succeeds.
Explore further: Golang Wait
Performance and Problems
RWMutex's performance degrades with increased number of CPU cores, a known issue discovered in the past.
This is a result of a GitHub issue, specifically #17973, which highlights the problem.
In essence, the more CPU cores you have, the worse RWMutex performs.
It's essential to be aware of this limitation when designing concurrent systems in Go.
The RWMutex's performance issues can significantly impact the overall performance of your application.
RWMutex is still a reliable choice for many use cases, but it's crucial to understand its limitations.
Real-World Examples
In Go, you can use the rwm.RLocker() function to restrict access to certain objects, preventing them from using the writer lock. This is useful for a stricter separation of roles.
For instance, you can use rwm.RLocker() to prevent certain objects from using the rwm.Lock() and rwm.Unlock() methods, only allowing access to the RLock() and RUnlock() methods. This is achieved by wrapping the methods as Lock() and Unlock(), which are the only interface methods declared in Locker.
By using rwm.RLocker(), you can ensure that certain objects only have read access to the lock, without granting them access to the writer lock. This can be particularly useful in scenarios where you need to prevent certain objects from modifying shared resources.
Real-World Examples
In real-world scenarios, you might need to restrict certain objects from using both read and write locks. This can be achieved by using the rwm.RLocker() method, which returns an instance of the Locker interface.

The Locker interface only provides access to the RLock() and RUnlock() methods, preventing objects from using the writer lock.
By using rwm.RLocker(), you can ensure a stricter separation of roles and prevent certain objects from accessing the writer lock.
To illustrate this, the rwm.RLocker() method can be used to rewrite the example code that restricts objects to only use RLock() and RUnlock().
Config Reader
When working with a config reader, it's essential to use RWMutex to handle concurrent access. Always match locks with unlocks to avoid deadlocks.
Using a live dashboard with frequent reads is a great example of RWMutex in action, where readers access freely and writes lock fully.
RWMutex allows multiple readers to access the data simultaneously, making it perfect for config readers that need to retrieve data frequently.
Featured Images: pexels.com


