Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the benefit of using RWMutex instead of Mutex?

Tags:

go

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?

like image 235
Alex Avatar asked Feb 19 '18 07:02

Alex


People also ask

Why do we need RWMutex?

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.

What is the difference between RWMutex and mutex in Golang?

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 .

What is 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"

What is RW_ Mutex?

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).


1 Answers

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.

like image 196
Peter Avatar answered Sep 22 '22 18:09

Peter