I am not sure when to use RWMutex and when to use Mutex.
Do you save resources if you use RWMutex instead of Mutex if you do more reads then writes?
I see some people use Mutex all the time no matter what they do, and some use RWMutex and run these methods:
func (rw *RWMutex) Lock() func (rw *RWMutex) Unlock() func (rw *RWMutex) RLock() func (rw *RWMutex) RUnlock()
instead of just:
func (m *Mutex) Lock() func (m *Mutex) Unlock()
If you save resources, is it that much of a difference that you should use RWMutex if you do more reads then writes?
You use this for use cases that are not defined in atomic. In either case locking is only required when writing. Multiple threads* can safely read the same value without a locking mechanism.
The most straightforward approach would be to use Mutex for locking your critical data. The RWMutex can be used if, and only if there are a limited number of concurrent readers of that data. Starting from a number of concurrent readers, it may become ineffective to use RWMutex .
RWMutex — Safely Allow Multiple Readers A read/write mutex allows all the readers to access the map at the same time, but a writer will lock out everyone else. package main. import ( "fmt" "sync"
The RWMutex is a unit which prevents parallel conflicting operations (which mutate same parts of an object. Basically, but not necessary, "write" operations), but allows parallel non-conflicting operations ("read" operations or "write" operations over independent parts of the object).
From the docs (emphasize mine):
A RWMutex is a reader/writer mutual exclusion lock. The lock can be held by an arbitrary number of readers or a single writer. The zero value for a RWMutex is an unlocked mutex.
In other words, readers don't have to wait for each other. They only have to wait for writers holding the lock.
A sync.RWMutex is thus preferable for data that is mostly read, and the resource that is saved compared to a sync.Mutex is time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With