From the Go docs:
A RWMutex is a reader/writer mutual exclusion lock. The lock can be held by an arbitrary number of readers or a single writer.
This introductory sentence is never followed by a definition of what a reader and writer may and may not do. Thus, I wonder whether a certain stretch of the definition is possible.
Suppose we have a set of many goroutines; let's call it S
. Each of the goroutines in S
has its own resources which it reads from and writes to frequently. Suppose I have one extra goroutine R
which routinely wants to scrape the state of the resources written by the goroutines in S
. Let's explore the two more obvious solutions to see where I am going.
- We can use a single mutex. However, the goroutines in
S
would needlessly compete for the lock, since each goroutine fromS
accesses only its own resources anyway. - Use one mutex for each goroutine in
S
. This eliminates needless competition and even givesR
the option to decide whether it needs to have locked all mutexex at once or merely each mutex at least once at some point in time. Requires some extra work however.
So my third idea is this: Let the goroutines in S
take the read lock of a sync.RWMutex
when they want to read or write (i.e. a generalized inclusive lock) and let R
take the write lock of that mutex when it wants to read (i.e. a generalized exclusive lock). In other words:
Is it safe to use the read lock of sync.RWMutex
for writing and its write lock for reading if the writes never race with each other by design?