goconcurrencymutex

Performance in Go: Mutex vs RWMutex


There are two types of mutex in Go: Mutex and RWMutex

From what I understand, we should only use RWMutex when there are many read operations and few write operations, to allow for concurrent reads. It also is more time-consuming to write-lock.

But what if I only use RWMutex and alternate using func Lock() / func Unlock() when I want to allow concurrent reads and func RLock / func RUnlock when I want to do the same as a normal Mutex. Is using RLock / RUnlock the same time as a normal mutex equivalent functions?

TLDR: Why use Mutex when RWMutex offers the same functionality with more options?


Solution

  • A RWMutex need to care about a lot of problems, for example writers starvation. A Mutex is much simpler and in fact used as a building block for a RWMutex.

    So in principle you could just use a RWMutex as a mutex, but then you would use the underlying Mutex with additional - in this case unnecessary - logic on top. Since concurrency is complicated enough, you usually strive to keep everything as simple and performant as possible, therefore using the simplest construct that fits your needs.